JAXB2

阅读更多
package com.benx.test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

public class JAXB2 {
	public static void main(String[] args) throws JAXBException, IOException {
		marshal();
		unmarshal();
	}
	

	static void marshal() throws JAXBException{
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Marshaller m = context.createMarshaller();
		
		Person p = new Person("我是谁", "工程师", new Date());
		//把生产的xml文件输出到标准流
		m.marshal(p, System.out);
	}
	
	static void unmarshal() throws JAXBException{
		String xml = "我是谁工程师";
		ByteArrayInputStream bos = new ByteArrayInputStream(xml.getBytes());
		
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Unmarshaller um = context.createUnmarshaller();
		Person p2 = (Person) um.unmarshal(bos);
		
		System.out.println();
		System.out.println(p2.name);
		
	}
}



@XmlRootElement
class Person {

	@XmlElement
	public String name;

	@XmlElement
	public String job;

	@XmlElement
	@XmlJavaTypeAdapter(TimeAdapter.class)
	public Date time;

	public Person() {
	}

	public Person(String name, String job, Date time) {
		super();
		this.name = name;
		this.job = job;
		this.time = time;
	}
}

/**
 * 时间转换
 * @author jin.xiong
 *
 */
class TimeAdapter extends XmlAdapter {

	private SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * java to xml 把Date转成日期字符形式
	 */
	public String marshal(Date arg0) throws Exception {
		Date date = (Date) arg0;
		return dateformat.format(date);
	}

	/**
	 * xml to java 把字符转成日期形式
	 */
	public Date unmarshal(String arg0) throws Exception {
		String time = (String) arg0;
		return dateformat.parse(time);
	}
}

你可能感兴趣的:(JAXB2)