一、简介
Jaxb(Java Architecture for XML Binding)是可以根据xml schema产生java类,也可以把java对象写入xml文件中的技术。
JAXB 2.0是JDK 1.6的组成部分。JAXB 2.2.3是JDK 1.7的组成部分,包括以下几个重要的Interface和Class
1. JAXBContext 是应用的入口,用来管理Java/xml的绑定信息
2. Marshaller 由Java对象序生成xml数据
3. Unmarshaller 由xml数据生成Java对象
二、简单使用示例
package jaxbTest;
//import ...
@XmlRootElement(name="Customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlAttribute
private Integer id;
@XmlElement
private String name;
@XmlElement
private Integer age;
@XmlElement
private List<String> accountIds;
//getter,setter and toString...
}
package jaxbTest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JaxbDemo {
private static JAXBContext jaxbContext = null;
static {
try {
jaxbContext = JAXBContext.newInstance(Customer.class);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void object2Xml(Customer customer, File file) throws JAXBException {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, file);
marshaller.marshal(customer, System.out);
}
public static Customer xml2Object(File file) throws JAXBException {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (Customer)unmarshaller.unmarshal(file);
}
public static void testMarshaller() throws JAXBException {
Customer customer = new Customer();
customer.setId(1);
customer.setName("Kent");
customer.setAge(25);
List<String> accountIds = new ArrayList<String>();
accountIds.add("123");
accountIds.add("456");
accountIds.add("789");
customer.setAccountIds(accountIds);
File file = new File("F:\\test\\jaxb_test.xml");
JaxbDemo.object2Xml(customer, file);
}
public static void testUnmarshaller() throws JAXBException {
File file = new File("F:\\test\\jaxb_test.xml");
Customer customer = JaxbDemo.xml2Object(file);
System.out.println(customer);
}
public static void main(String[] args) throws Exception {
testMarshaller();
//testUnmarshaller();
}
}
调用testMarshaller()结果生成xml数据
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer id="1">
<name>Kent</name>
<age>25</age>
<accountIds>123</accountIds>
<accountIds>456</accountIds>
<accountIds>789</accountIds>
</Customer>
调用testUnmarshaller()生成java对象
Customer [id=1, name=Kent, age=25, accountIds=[123, 456, 789]]