1. 程式人生 > >WebService系列部落格{九}[JAXBContext---java和xml的互相轉換]

WebService系列部落格{九}[JAXBContext---java和xml的互相轉換]

java和xml的互相轉換,依靠強大的JAXBContext可以輕鬆實現。

下面通過一個簡單案例學習一下JAXBContext

首先準備好一個JavaBean供實驗:

注意

1、類檔案註解:@XmlRootElement不可缺少

2、2個Student的構造方法不能少

@XmlRootElement
public class Student {
	private String name;
	private String width;
	private String height;
	private int age;
	
	
	public Student(String name, String width, String height, int age) {
		super();
		this.name = name;
		this.width = width;
		this.height = height;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getWidth() {
		return width;
	}
	public void setWidth(String width) {
		this.width = width;
	}
	public String getHeight() {
		return height;
	}
	public void setHeight(String height) {
		this.height = height;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
		super();
	}
	
}

JavaToXml:
	@Test
	public void test01(){
		try {
			JAXBContext jc = JAXBContext.newInstance(Student.class);
			Marshaller ms = jc.createMarshaller();
			Student st = new Student("zhang", "w", "h", 11);
			ms.marshal(st, System.out);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

XmlToJava

	//xml轉換Java
	@Test
	public void test02() throws JAXBException{
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>11</age><height>h</height><name>zhang</name><width>w</width></student>";
		JAXBContext jc = JAXBContext.newInstance(Student.class);
		Unmarshaller unmar = jc.createUnmarshaller();
		Student stu = (Student) unmar.unmarshal(new StringReader(xml));
		System.out.println(stu.getName());
	}