tang7526
3/18/2016 - 9:11 AM

[JAVA][JAXB] 物件轉XML

[JAVA][JAXB] 物件轉XML

// 這裡定義一個Boy類別,並設定成XML root,訪問種類設定FIELD,表示會將類別裡的所有成員變數都映射成XML。
// 接著在main()裡,示範如何使用JAXB將這個Boy物件轉成XML;及示範如果使用JAXB將XML轉成物件。

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)  
public class Boy {     
    String name = "CY";  
}  

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class main {
	public static void main(String[] args) throws JAXBException {
		JAXBContext jaxb = JAXBContext.newInstance(Boy.class);
		Marshaller marshaller = jaxb.createMarshaller();
		Unmarshaller unmarshaller = jaxb.createUnmarshaller();

		marshaller.marshal(new Boy(), System.out);
		System.out.println();
		
		String xml = "<boy><name>David</name></boy>";
		Boy boy2 = (Boy)unmarshaller.unmarshal(new StringReader(xml));
		System.out.println(boy2.name);
	}
}