使用JAXB處理JAVA和XML

林竟發表於2013-11-30

使用JAXB完成Java和XML的相互轉化:

java-->xml:編排,marshal

xml-->java:反編排,unmarshal

package org.itat.xml;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.junit.Test;

public class TestJaxb {

	/**
	 * marshal編排,java-->xml
	 */
	@Test
	public void test01() {
		try {
			//1.建立JAXBContext例項
			JAXBContext ctx = JAXBContext.newInstance(Student.class);
			//2.建立marshaller例項
			Marshaller marshaller = ctx.createMarshaller();
			//3.建立student物件,並將該物件轉換為xml
			Student student = new Student(1, "姚雙雙", 25, new Classroom(1, "08計算機應用技術", 2008));
			//4.將java-->xml,並輸出
			marshaller.marshal(student, System.out);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	/*
	 * 執行結果:
	 * <?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><age>25</age><classroom><grade>2008</grade><id>1</id><name>08計算機應用技術</name></classroom><id>1</id><name>姚雙雙</name></student>
	 */
	
	/**
	 * unmarshal反編排,xml-->java
	 */
	@Test
	public void test02() {
		try {
			//要轉換的xml
			String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>25</age><classroom><grade>2008</grade><id>1</id><name>08計算機應用技術</name></classroom><id>1</id><name>姚雙雙</name></student>";
			//1.建立JAXBContext例項
			JAXBContext ctx = JAXBContext.newInstance(Student.class);
			//2.建立unmarshaller例項
			Unmarshaller um = ctx.createUnmarshaller();
			//3.讀入xml,並將xml-->java
			Student student = (Student)um.unmarshal(new StringReader(xml));
			//4.輸出
			System.out.println(student.getName() + ", " + student.getClassroom().getName());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	/*
	 * 執行結果:姚雙雙, 08計算機應用技術
	 * 
	 */
}

相關文章