这是我可以生成的XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
<student studentId="1">
<firstName>PEsho</firstName>
<lastName>Peshev</lastName>
<egn>521521512</egn>
<city>So</city>
<mark>5.56</mark>
<degree>
<university>Test1</university>
</degree>
</student>
<student studentId="1">
<firstName>Mesho</firstName>
<lastName>Meshev</lastName>
<egn>521521521</egn>
<city>Va</city>
<mark>5.56</mark>
<degree>
<university>Test2</university>
</degree>
</student>
我想做的是在学位元素中,大学是属性,而不是元素。这是我正在使用的代码: Student.class
@XmlRootElement(name = "student")
@XmlAccessorType (XmlAccessType.FIELD)
public class Student{
@XmlAttribute
private String studentId;
private String firstName;
private String lastName;
private String egn;
private String city;
private double mark;
private Degree degree;
getters, setters .. }
Students.class:
@XmlRootElement(name = "students")
@XmlAccessorType (XmlAccessType.FIELD)
public class Students {
@XmlElement(name = "student")
private List<Student> students = null;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
} }
Degree.class
@XmlRootElement(name = "degree")
public class Degree {
private String university;
setters, getters
}
编组程序:
JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Marshal the employees list in console
jaxbMarshaller.marshal(students, System.out);
//Marshal the employees list in file
jaxbMarshaller.marshal(students, new File("file.xml"));
问题是当我m trying to add in a Degree.class @XmlAttribute to the university field I
得到此异常时:
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "university"
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
尝试将XmlAccessType.FIELD
属性添加到Degree类。
示例:
@XmlRootElement(name = "degree")
@XmlAccessorType(XmlAccessType.FIELD)
public class Degree {
@XmlAttribute
private String university;
setters, getters
}