JAXB解组示例(将XML转换为对象)

借助UnMarshaller界面, 我们可以将对象解组(读取)为xml文档。
在此示例中, 我们将把简单的xml文档转换为java对象。
【JAXB解组示例(将XML转换为对象)】让我们看看将XML文档转换为Java对象的步骤。

  • 创建POJO或绑定模式并生成类
  • 创建JAXBContext对象
  • 创建Unmarshaller对象
  • 调用解组方法
  • 使用POJO的getter方法访问数据
Unmarshaller示例:将xml文档转换为Java对象
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>

POJO课程
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.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class XmlToObject { public static void main(String[] args) { try { File file = new File("question.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Question.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Question que= (Question) jaxbUnmarshaller.unmarshal(file); System.out.println(que.getId()+" "+que.getQuestionname()); System.out.println("Answers:"); List< Answer> list=que.getAnswers(); for(Answer ans:list) System.out.println(ans.getId()+" "+ans.getAnswername()+""+ans.getPostedby()); } catch (JAXBException e) { e.printStackTrace(); } } }

输出:
1 What is java? Answers: 101 java is a programming language ravi 102 java is a platform john

    推荐阅读