标签:
1.将 xml 文件中的各个节点和属性信息创建对应的Java模型。2.在Java模型中的创建与 xml 文件对应的节点和属性需要用注解来表示。
@XmlRootElement 将一个Java类映射为一段XML的根节点
@XmlAccessorType 定义映射这个类中的何种类型需要映射到XML。可接收四个参数,分别是:
XmlAccessType.PROPERTY:映射这个类中的属性(get/set方法)到XML</items>
3.废话不多说了,我们直接上一个非常简单的例子程序。
3.1两个基本的POJO类。
package com.npf.jaxb; public class Classroom { private int id; private String name; }
package com.npf.jaxb; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Student { private int id; private String name; private int age; private Classroom room;} 3.2测试方法
package com.npf.jaxb; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.junit.Test; public class JAXBTest { @Test public void object2xml() throws JAXBException{ JAXBContext jaxbContext = JAXBContext.newInstance(Student.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Student student = new Student(1, "zhangsan",1,new Classroom(1,"computer")); marshaller.marshal(student, System.out); } @Test public void xml2object() throws JAXBException{ JAXBContext jaxbContext = JAXBContext.newInstance(Student.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<student><age>1</age><id>1</id><name>zhangsan</name><room><id>1</id>" + "<name>computer</name></room></student>"; Student student = (Student) unmarshaller.unmarshal(new StringReader(xml)); System.out.println(student.getName()+","+student.getRoom().getName()); } }
标签:
原文地址:http://blog.csdn.net/pfnie/article/details/51344324