借助于Marshaller界面, 我们可以将对象编组(写入)到xml文档中。在上一页中, 我们看到了将对象转换为xml的简单示例。
在此示例中, 我们将把对象转换为具有原语, 字符串和集合对象的xml。
让我们看看将Java对象转换为XML文档的步骤。
- 创建POJO或绑定模式并生成类
- 创建JAXBContext对象
- 创建Marshaller对象
- 通过使用set方法创建内容树
- 调用元帅方法
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Question {
private int id;
private String questionname;
private List<Answer> answers;
public Question() {}
public Question(int id, String questionname, List<Answer> answers) {
super();
this.id = id;
this.questionname = questionname;
this.answers = answers;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getQuestionname() {
return questionname;
}
public void setQuestionname(String questionname) {
this.questionname = questionname;
}
@XmlElement
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {}
public Answer(int id, String answername, String postedby) {
super();
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class ObjectToXml {
public static void main(String[] args) throws Exception{
JAXBContext contextObj = JAXBContext.newInstance(Question.class);
Marshaller marshallerObj = contextObj.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Answer ans1=new Answer(101, "java is a programming language", "ravi");
Answer ans2=new Answer(102, "java is a platform", "john");
ArrayList<Answer> list=new ArrayList<Answer>();
list.add(ans1);
list.add(ans2);
Question que=new Question(1, "What is java?", list);
marshallerObj.marshal(que, new FileOutputStream("question.xml"));
}
}
输出:
生成的xml文件将如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<question id="1">
<answers>
<answername>java is a programming language</answername>
<id>101</id>
<postedby>ravi</postedby>
</answers>
<answers>
<answername>java is a platform</answername>
<id>102</id>
<postedby>john</postedby>
</answers>
<questionname>What is java?</questionname>
</question>
评论前必须登录!
注册