使用JAXB進行JavaBean物件與XML檔案的相互轉化
思想:父標籤相當於一個物件,子標籤相當於物件的屬性,然後迴圈巢狀。
JAXBContext類,是應用的入口,用於管理XML/Java繫結資訊。
Marshaller介面,將Java物件序列化為XML資料。
Unmarshaller介面,將XML資料反序列化為Java物件。
一、註解:
指定一個欄位或get/set方法對映到XML的節點(註解在方法上)。
定義對映這個類中的何種型別需要對映到XML。可接收四個引數,分別是(註解在類上):
2.1.XmlAccessType. NONE:
所有欄位或屬性都不能繫結到 XML,除非使用一些 JAXB 註釋專門對它們進行註釋。被這個註解的類,如果你想類中的屬性編入到
2.2.XmlAccessType.PUBLIC_MEMBER:
(預設)每個公共獲取方法/設定方法對和每個公共欄位將會自動繫結到 XML,除非由 XmlTransient 註釋。被XmlTransient註解以後就不編入Xml檔案中。如果使用預設且在類屬性中使用@XmlElement 註解,那麼會出現資料重複編入Xml情況。
2.3. XmlAccessType.FIELD:
JAXB 繫結類中的每個非靜態、非瞬態欄位將會自動繫結到 XML,除非由 XmlTransient 註釋。
2.4. XmlAccessType.PROPERTY:
JAXB 繫結類中的每個獲取方法/設定方法對將會自動繫結到 XML,除非由 XmlTransient 註釋。
在原來封裝的基礎上,再封裝一個(加多一層)name,這裡要求被註解的屬性必須是集合屬性。
對要編入Xml的類屬性進行進行排序,注意,這裡的ABC指的是JavaBean類屬性實體,也就是 A a 中的a。而不是@XmlElement
()裡面所指的物件
二、配置
1.Marshaller.set(Marshaller.JAXB_ENCODING,”GBK”) :
設定格式為GBK。設定以後,xml檔案頭的encoding會顯示為GBK
2.Marshaller.set(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,”fem.shema.xsd”):
設定非名稱空間:
<WH000411 xsi:noNamespaceSchemaLocation="fem.schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> |
3.如果擁有多個名稱空間的話,使用package-info.java包級別的註解
<?xml version="1.0" encoding="UTF-8" standalone="no"?><GzeportTransfer xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:n1="http://www.altova.com/samplexml/other-namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> |
具體如下:在GzeportTransfer物件同級包下新建一個package-info.java(這個檔案一般是建立包的時候一同建立,後期無法直接建立,要的話可以直接在桌面建立一個,然後將附件進來),package-info.java檔案的內容如下:注意,註解是在包上面,且無需其他程式碼
@XmlSchema( xmlns={ @XmlNs(prefix="n1",namespaceURI="http://www.altova.com/samplexml/other-namespace"), @XmlNs(prefix="ds",namespaceURI="http://www.w3.org/2000/09/xmldsig#"), @XmlNs(prefix="xsi",namespaceURI="http://www.w3.org/2001/XMLSchema-instance") } ) /*這裡由於是包級別的註解,所以要獨立成立一個包,避免影響其他*/ package com.ceb.gztradeio.bo.namespace; import javax.xml.bind.annotation.*; |
注意:該方法必須為JDK1.7如果為JDK1.6的話,那麼必須新增兩個jar包,分別為jaxb-core-2.2.7.jar和jaxb-impl-2.2.7.jar
三、簡單例子
Bean物件
Student物件
package com.test.Jaxb; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; @XmlAccessorType(XmlAccessType.NONE) public class Student { java.lang.String name;//姓名 String sex;//性別 int number;//學號 String className;//班級 Set<String> hobby;//愛好 public Student(String name, String sex, int number, String className, Set<String> hobby) { super(); this.name = name; this.sex = sex; this.number = number; this.className = className; this.hobby = hobby; } public Student() { } @XmlAttribute(name="name") public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } @XmlElement(name="sex") public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @XmlAttribute(name="number") public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @XmlElement(name="ClassName") public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @XmlElementWrapper(name="bobbys") @XmlElement(name="hobby") public Set<String> getHobby() { return hobby; } public void setHobby(Set<String> hobby) { this.hobby = hobby; } @Override public String toString() { return "Student [name=" + name + ", sex=" + sex + ", number=" + number + ", className=" + className + ", hobby=" + hobby + "]"; } //對於擁有get/set方法的屬性,註解不能定義在屬性的定義上,只能在get或者set上定義一個就可以,否則出錯。 } |
List物件
package com.test.Jaxb; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="List") public class StudentList { Set<Student> students;//所有學生資訊集合 @XmlElement(name = "student") public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } } |
1.JavaBean轉化為XML
package com.test.Jaxb; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class StudentToXML { public static String beantoXml(Object obj,Class<?> load) throws JAXBException{ JAXBContext context = JAXBContext.newInstance(load); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK"); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "fem.schema.xsd"); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); return writer.toString(); } public static void main(String[] args) throws JAXBException, IOException{ Set<String> hobby = new LinkedHashSet<String>(); hobby.add("狼求"); hobby.add("yingyue"); hobby.add("pingpanqiu");//新增body物件 Set<Student> studentList = new LinkedHashSet<Student>(); Student st1 = new Student("張三","娜娜",1001,"尖子班",hobby); studentList.add(st1); Student st2 = new Student("lisi","男",1002,"普通版",hobby); studentList.add(st2); Student st3 = new Student("王五","女",1003,"普通版",hobby); studentList.add(st3);//添students物件 StudentList students = new StudentList(); students.setStudents(studentList); String str = StudentToXML.beantoXml(students, StudentList.class); String xmlPath="D:/testConfig.xml"; BufferedWriter bfw = new BufferedWriter(new FileWriter(new File(xmlPath))); bfw.write(str); bfw.close(); } } |
生成的結果如下
<?xml version="1.0" encoding="GBK" standalone="yes"?> <List xsi:noNamespaceSchemaLocation="fem.schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <student number="1001" name="張三"> <ClassName>尖子班</ClassName> <bobbys> <hobby>狼求</hobby> <hobby>yingyue</hobby> <hobby>pingpanqiu</hobby> </bobbys> <sex>娜娜</sex> </student> <student number="1002" name="lisi"> <ClassName>普通版</ClassName> <bobbys> <hobby>狼求</hobby> <hobby>yingyue</hobby> <hobby>pingpanqiu</hobby> </bobbys> <sex>男</sex> </student> <student number="1003" name="王五"> <ClassName>普通版</ClassName> <bobbys> <hobby>狼求</hobby> <hobby>yingyue</hobby> <hobby>pingpanqiu</hobby> </bobbys> <sex>女</sex> </student> </List> |
2.將xml內容轉化為物件
package com.test.Jaxb; import java.io.File; import java.util.Iterator; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class XmlToStudent { public static void main(String[] args){ String filepath = "D:/testConfig.xml"; StudentList students = xmlToJavabean(filepath, StudentList.class); System.out.println(students.getStudents()); } public static <T> T xmlToJavabean(String filepath,Class<T> c){ T t = null; try { File xmlFile = new File(filepath); JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); t = (T)unmarshaller.unmarshal(xmlFile);; } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return t; } } |
結果如下
[Student [name=王五, sex=女, number=1003, className=普通版, hobby=[狼求, pingpanqiu, yingyue]], Student [name=張三, sex=娜娜, number=1001, className=尖子班, hobby=[狼求, pingpanqiu, yingyue]], Student [name=lisi, sex=男, number=1002, className=普通版, hobby=[狼求, pingpanqiu, yingyue]]] |