JAXB是Java Architecture for XML Binding的縮寫。使用JAXB注解將Java對象轉換成XML文件。在這篇教程中,我們將會展示如何使用JAXB來做以下事情:
1. marshall 將java對象轉化成xml文件
2. unmarshalling 將xml內容轉換成java對象
JAXB 注解(Annotation)
如果一個對象需要被轉換成XML文件,或者從XML文件中生成,該對象需要用JAXB注解來標注。這些注解光憑名字就知道是什么意思了。具體可參考官網:jaxb guide
package com.jaxb.core; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public 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; } }
對象轉換成XML
JAXB marshalling例子,將customer對象轉換成XML文件。jaxbMarshaller.marshal()包含了許多重載方法,哪個輸出符合你的要求就選擇哪個方法。
package com.jaxb.core; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JAXBExample { public static void main(String[] args) { Customer customer = new Customer(); customer.setId(100); customer.setName("benson"); customer.setAge(23); 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(); } } }
輸出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer id="100"> <age>23</age> <name>benson</name> </customer>
XML轉換成對象:
JAXB unmarshalling例子,將XML文件內容轉換成customer對象。jaxbMarshaller.unmarshal()包含了許多重載方法,哪個適合你的輸出,你就選擇哪個方法。
package com.jaxb.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
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();
}
}
}
