JAXB学习

来源:互联网 发布:白矮星 表面 知乎 编辑:程序博客网 时间:2024/05/16 18:36

JAXB(Java Api for XML Binding).是一项可以根据XML Schema产生Java类的技术。通过该技术,可以轻松的实现XML和JAVA对象的互转。

首先定义个People类,这里需要通过java的Annotation来实现

package com.test.jaxb;import java.util.Date;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="people")public class People {private String name = "";private int age = 0;private Date birthday = null;@XmlAttribute(name="name")public String getName() {return name;}public void setName(String name) {this.name = name;}@XmlElement(name="age")public int getAge() {return age;}public void setAge(int age) {this.age = age;}@XmlElement(name="birthday")public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}


在来个实现方式:

package com.test.jaxb;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;public class JAXBTest {public static void main(String[] args) {JAXBTest jt = new JAXBTest();// 构造对象People people = new People();people.setName("popo");people.setAge(88);try {people.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1949-10-01"));} catch (ParseException e) {e.printStackTrace();}// 对象转换成为XMLjt.beanToXml(people);// 读取XML转换成对象People p = jt.XMLToBean("d://people.xml", People.class);// 输出对象System.out.println(p.getName());System.out.println(p.getAge());System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(p.getBirthday()));}public <T> void beanToXml(T dto){try {JAXBContext context = JAXBContext.newInstance(dto.getClass());Marshaller marshaller = context.createMarshaller();FileOutputStream fos = new FileOutputStream(new File("d://people.xml"));marshaller.marshal(dto, fos);fos.close();} catch (JAXBException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@SuppressWarnings("unchecked")public <T> T XMLToBean(String xmlPath, Class<T> c){T t = null;try {JAXBContext context = JAXBContext.newInstance(c);Unmarshaller unmarshaller = context.createUnmarshaller();t = (T) unmarshaller.unmarshal(new File(xmlPath));} catch (JAXBException e) {e.printStackTrace();}return t;}}