2016-01-13 314 views
2

这里是我可以产生XML:JAXB添加属性元素

<?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 m如果此异常:

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" 

有人可以帮我解决这个问题?

回答

1

尝试将XmlAccessType.FIELD属性添加到您的Degree类。

实施例:

@XmlRootElement(name = "degree") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Degree { 

    @XmlAttribute 
    private String university; 
    setters, getters 
}