读书人

JAXB 的 hello world 示范

发布时间: 2012-12-21 12:03:49 作者: rapoo

JAXB 的 hello world 示例
JAXB(Java Architecture for XML Binding简称JAXB)允许Java开发人员将Java类映射为XML表示方式。JAXB提供两种主要特性:将一个Java对象序列化为XML,以 及反向操作,将XML解析成Java对象。换句话说,JAXB允许以XML格式存储和读取数据,而不需要程序的类结构实现特定的读取XML和保存XML的 代码。



Customer.java

package com.mkyong.core; 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;} @XmlElementpublic void setName(String name) {this.name = name;} public int getAge() {return age;} @XmlElementpublic void setAge(int age) {this.age = age;} public int getId() {return id;} @XmlAttributepublic void setId(int id) {this.id = id;} }



JAXBExample.java
package com.mkyong.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("mkyong");  customer.setAge(29);   try { File file = new File("C:\\file.xml");JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printedjaxbMarshaller.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>29</age>    <name>mkyong</name></customer>


将XML转为对象
package com.mkyong.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();  } }}


输出

Customer [name=mkyong, age=29, id=100]


文章转自:http://www.oschina.net/code/snippet_12_5581

读书人网 >编程

热点推荐