参考网页:http://www.mkyong.com/java/jaxb-hello-world-example/
JAXB完整教程:https://jaxb.java.net/tutorial/1.JAXB 依赖maven项目使用JAXB首先需要添加jaxb api和jaxb impl,jaxb core(因为jaxb api 2.2.11 版本之后不再支持annomationReader,详见:http://stackoverflow.com/questions/27046836/why-has-annotationreader-been-removed-from-jaxb-reference-implementation):jaxb api的maven dependency可以在这里找到:http://mvnrepository.com/artifact/javax.xml/jaxb-apijaxb impl的maven dependency可以在这里找到:http://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impljaxb core的maven dependency可以在这里找到:http://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core这里使用最新的版本,添加如下代码到pom.xml的dependencies当中:com.sun.xml.bind jaxb-core 2.2.11 javax.xml jaxb-api 2.1 com.sun.xml.bind jaxb-impl 2.2.11
2.JAXB注释
需要进行xml转换的类必须用JAXB注释(JAXB annotation)进行注释。package com.mypackage;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Customer { String name; int age; int id; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getAge() { return age; } @XmlElement public void setAge(int age) { this.age = age; } public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; } @Override public String toString() { return "Customer [name=" + name + ", age=" + age + ", id=" + id + "]"; }}
3.将对象转换成XML
JAXB编组(marshall)对象成XML。package com.mypackage;import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;public class JAXBMarshallExample { public static void main(String[] args) { Customer customer = new Customer(); customer.setId(1000); customer.setName("moon"); customer.setAge(18); try { File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); } catch (JAXBException e) { e.printStackTrace(); } }}
输出结果:
18 moon
4.将XML转换成对象
JAXB解组(unmarshall)XML成对象。package com.mypackage;import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Unmarshaller;public class JAXBUnmarshallExample { public static void main(String[] args) { try { File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); System.out.println(customer); } catch (JAXBException e) { e.printStackTrace(); } }}
程序输出:
Customer [name=moon, age=18, id=1000]