Java如何在JAXB中将bean属性映射到XML属性?
在此示例中,您将学习如何在JAXB中将bean/pojo属性定义为XML属性。为了将属性定义为XML属性,我们使用了@XmlAttribute注释。在Student下面的类中,该id属性将定义为student根元素的属性。而nameandgrade属性将是的元素student。
package org.nhooo.example.jaxb; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Student { private Integer id; private String name; private Integer grade; @XmlAttribute public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } }
在这里,我们可以使用该程序将Studentbean转换为XML文档。
package org.nhooo.example.jaxb; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.FileWriter; import java.io.IOException; public class JAXBElementAttribute { public static void main(String[] args) { Student student = new Student(); student.setId(1); student.setName("Alice"); student.setGrade(12); try { JAXBContext context = JAXBContext.newInstance(Student.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(student, new FileWriter("Student.xml")); } catch (JAXBException | IOException e) { e.printStackTrace(); } } }
当您运行该程序时,Student.xml将创建一个名为的文件,其中包含以下内容:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <student id="1"> <grade>12</grade> <name>Alice</name> </student>