有两个实体对象“意见”和“回复”,它们之间是一对多的关系
@XmlAccessorType(XmlAccessType.FIELD)
public class Advice {
@XmlAttribute
protected String filename;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void setReplies(List<Reply> replies) {
this.replies = replies;
}
public List<Reply> getReplies() {
return replies;
}
@XmlElement
protected String filepath;
@XmlElement
protected String content;
@XmlElementWrapper(name="replies")
@XmlElement(name = "value")
private List<Reply> replies ;
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Reply {
@XmlAttribute
private String content;
@XmlAttribute
private int status;
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
}
public static void main(String[] args) throws JAXBException, FileNotFoundException {
JAXBContext jc = JAXBContext.newInstance("Advice");
Advice a= new Advice();
a.setFilename("aaa.java");
a.setFilepath("c:\\");
a.setContent("content");
Reply reply1 = new Reply();
reply1.setContent("xxx");
reply1.setStatus(0);
Reply reply2 = new Reply();
reply2.setContent("yyyy");
reply2.setStatus(1);
List<Reply> replies = new ArrayList<Reply>();
replies.add(reply1);
replies.add(reply2);
a.setReplies(replies);
JAXBElement usersE = new JAXBElement<Advice>(new QName("", "advice"), Advice.class, null, a);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal( usersE,new FileOutputStream("c:\\test.xml"));
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <advice filename="aaa.java">
<filepath>c:\</filepath>
<content>content</content>
- <replies>
<value status="0" content="xxx" />
<value status="1" content="yyyy" />
</replies>
</advice>