JAXB是Java Architecture for XML Binding的縮寫,用於在Java類與XML之間建立映射,能夠幫助開發者很方便的將XML和Java對象進行相互轉換。
本文以一個簡單的例子介紹JAXB的使用,首先我們需要了解一下JAXB常用的API。
Unmarshaller接口,將XML數據反序列化為Java對象。
@XmlType,將Java類或枚舉類型映射到XML模式類型
@XmlAccessorType(XmlAccessType.FIELD),控制字段或屬性的序列化。FIELD表示JAXB將自動綁定Java類中的每個非靜態的(static)、非瞬態的(由@XmlTransient標注)字段到XML。其他值還有XmlAccessType.PROPERTY和XmlAccessType.NONE。 @XmlAccessorOrder,控制JAXB 綁定類中屬性和字段的排序 @XmlJavaTypeAdapter,使用定制的適配器(即擴展抽象類XmlAdapter並覆蓋marshal()和unmarshal()方法),以序列化Java類為XML。 @XmlElementWrapper ,對於數組或集合(即包含多個元素的成員變量),生成一個包裝該數組或集合的XML元素(稱為包裝器)。 @XmlRootElement,將Java類或枚舉類型映射到XML元素。 @XmlElement,將Java類的一個屬性映射到與屬性同名的一個XML元素。 @XmlAttribute,將Java類的一個屬性映射到與屬性同名的一個XML屬性。我們需要進行綁定的Java Bean內容如下:
Employee.java
package net.csdn.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(name = "Employee", propOrder = { "name", "age", "role", "gender" })
public class Employee {
private String name;
private String gender;
private int age;
private String role;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender="
+ this.gender + " Role=" + this.role;
}
}
需要轉換為Java對象的XML文件內容如下:
employee.xml
Pankaj
29
Java Developer
Male
接下來編寫測試用例代碼:
TestJAXB.java
package net.csdn.test;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import net.csdn.beans.Employee;
import org.junit.Test;
public class TestJAXB {
@Test
public void testXml2Obj() throws Exception {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("employee.xml");
byte[] bytes = new byte[is.available()];
is.read(bytes);
String xmlStr = new String(bytes);
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employee emp = (Employee) unmarshaller.unmarshal(new StringReader(xmlStr));
System.out.println(emp);
}
@Test
public void testObj2Xml() {
Employee emp = new Employee();
emp.setAge(10);
emp.setGender("Male");
emp.setName("Jane");
emp.setRole("Teacher");
String xmlStr = TestJAXB.convertToXml(emp,"utf-8");
System.out.println(xmlStr);
}
public static String convertToXml(Object obj, String encoding) {
String result = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
運行testObj2Xml測試方法,控制台輸出:
<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%20standalone%3D%22yes%22%3F%2D%2D%3E--> <employee> <name>Jane</name> <age>10</age> <role>Teacher</role> <gender>Male</gender> </employee> </code>
運行testXml2Obj測試方法,控制台輸出:
Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer
注:本例中使用JUnit4作為單元測試工具,在Eclipse中點擊Window->Show View->OutLine菜單打開outline視圖,分別在testXml2Obj和testObj2Xml方法上點擊右鍵->Run As->JUnit Test即可。