JAXB 简单Demo
jaxb.JaxbDemo
package jaxb;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import pojo.People;public class JaxbDemo {// 编组数据public static void marshalData() throws JAXBException, IOException {JAXBContext context = JAXBContext.newInstance(People.class);Marshaller marshaller = context.createMarshaller();marshaller.setProperty(Marshaller.JAXB_ENCODING, "gb2312");// 编码格式marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串// 是否省略xml头信息(<?xml version="1.0" encoding="gb2312" standalone="yes"?>)marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);People people = new People();people.setLogo("=====");people.setId(1);people.setName("son");People father = new People();father.setId(2);father.setName("father");people.setFather(father);FileOutputStream os = new FileOutputStream("People.xml");marshaller.marshal(people, os);os.close();}// 解组数据public static void unmarshalData() throws JAXBException, FileNotFoundException {JAXBContext context = JAXBContext.newInstance(People.class);Unmarshaller unmarshaller = context.createUnmarshaller();People p = (People) unmarshaller.unmarshal(new FileInputStream("People.xml"));System.out.println(p.getId() + " : " + p.getName());}}
package pojo;public class AbstractPeople {private String logo;public String getLogo() {return logo;}public void setLogo(String logo) {this.logo = logo;}}
package pojo;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "People")@XmlAccessorType(XmlAccessType.FIELD)public class People extends AbstractPeople{private int id;private String name;private People father;public People() {}public People(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public People getFather() {return father;}public void setFather(People father) {this.father = father;}}
<?xml version="1.0" encoding="gb2312" standalone="yes"?><People> <logo>=====</logo> <id>1</id> <name>son</name> <father> <id>2</id> <name>father</name> </father></People>