XML - JAXB示例

襲冷發表於2014-06-30

一、簡介

    JAXB 即 Java Architecture for XML Binding,它提供一個繫結的編譯器和一個執行時框架用來支援 XML 和 Java 物件的雙向對映。


二、示例

    1、marshaller

        程式碼:

		JAXBContext ctx = JAXBContext.newInstance(User.class);
		Marshaller marshaller = ctx.createMarshaller();
		User user = new User(1, "admin", new Role(1, "System", "System Management"));
		marshaller.marshal(user, System.out);
        結果:

	<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
	<user>
		<id>1</id>
		<name>admin</name>
		<role>
			<id>1</id>
			<name>System</name>
			<note>System Management</note>
		</role>
	</user>

    2、unmarshaller

        程式碼:

		JAXBContext ctx = JAXBContext.newInstance(User.class);
		Unmarshaller unmarshaller = ctx.createUnmarshaller();
		String xml = 
				"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + 
				"<user>" +
				"	<id>1</id>" +
				"	<name>admin</name>" +
				"	<role>" +
				"		<id>1</id>" +
				"		<name>System</name>" +
				"		<note>System Management</note>" +
				"	</role>" +
				"</user>"; 
		User user  = (User) unmarshaller.unmarshal(new StringReader(xml));
		System.out.println(user);

        結果:

    User [id=1, name=admin, role=Role [id=1, name=System, note=System Management]]


三、附錄

import javax.xml.bind.annotation.XmlRootElement;

/**
 * 實體, 需註解@XmlRootElement,否則異常javax.xml.bind.MarshalException
 */
@XmlRootElement
public class User {
	private int id;
	private String name;
	private Role role;
	
    /** getter and setter **/
	
}
public class Role {
	private int id;
	private String name;
	private String note;
	
    /** getter and setter **/
	
}
 
 
 

相關文章