JAXB完成XML與Java對象的互轉

來源:互聯網
上載者:User

這段時間都老忙了,甚至連周末所有人員都在趕產品的進度,想想連續上12天班,人都有點暈了!到這會兒終於有點時間,所以準備和大家分享一下JAXB,會不會有人覺得有點陌生呢?沒事,這裡跟大伙兒簡單的描述一下:

JAXB(Java Architecture for XML Binding) 是一個業界的標準,是一項可以根據XML Schema產生Java類的技術。該過程中,JAXB也提供了將XML執行個體文檔反向產生Java對象樹的方法,並能將Java對象樹的內容重新寫到XML執行個體文檔。從另一方面來講,JAXB提供了快速而簡便的方法將XML模式綁定到Java表示,從而使得Java開發人員在Java應用程式中能方便地結合XML資料和處理函數。

基本知識就說這麼多,咱們來點實際的,準備上代碼了:

/** * @Description:  * * @Title: Student.java * @Package com.joyce.bean * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午02:51:41 * @version V2.0 */package com.joyce.bean;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;/** * @Description: 學生實體類 *  * @ClassName: Student * @Copyright: Copyright (c) 2014 *  * @author Comsys-LZP * @date 2014-6-10 下午02:51:41 * @version V2.0 */@XmlRootElement(name="Student")public class Student {/** * 姓名 */private String name;/** * 性別 */private String sex;/** * 年齡 */private Integer age;/** * @return the name */public String getName() {return name;}/** * @param name *            the name to set */@XmlAttributepublic void setName(String name) {this.name = name;}/** * @return the sex */public String getSex() {return sex;}/** * @param sex *            the sex to set */@XmlElementpublic void setSex(String sex) {this.sex = sex;}/** * @return the age */public Integer getAge() {return age;}/** * @param age *            the age to set */@XmlElementpublic void setAge(Integer age) {this.age = age;}/** * @param name * @param sex * @param age */public Student(String name, String sex, Integer age) {super();this.name = name;this.sex = sex;this.age = age;}/** *  */public Student() {super();}}

再來一個:
/** * @Description:  * * @Title: Teacher.java * @Package com.joyce.bean * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午04:29:23 * @version V2.0 */package com.joyce.bean;import java.util.List;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;/** * @Description: 教師實體類 *  * @ClassName: Teacher * @Copyright: Copyright (c) 2014 *  * @author Comsys-LZP * @date 2014-6-10 下午04:29:23 * @version V2.0 */@XmlRootElement(name="Teacher")public class Teacher {/** * 姓名 */private String name;/** * 性別 */private String sex;/** * 年齡 */private Integer age;/** * 學生 */private List<Student> students;/** * @return the name */public String getName() {return name;}/** * @param name *            the name to set */@XmlElementpublic void setName(String name) {this.name = name;}/** * @return the sex */public String getSex() {return sex;}/** * @param sex *            the sex to set */@XmlElementpublic void setSex(String sex) {this.sex = sex;}/** * @return the age */public Integer getAge() {return age;}/** * @param age *            the age to set */@XmlElementpublic void setAge(Integer age) {this.age = age;}/** * @return the students */public List<Student> getStudents() {return students;}/** * @param students *            the students to set */@XmlElement(name="Student")public void setStudents(List<Student> students) {this.students = students;}/** *  */public Teacher() {super();}/** * @param name * @param sex * @param age */public Teacher(String name, String sex, Integer age) {super();this.name = name;this.sex = sex;this.age = age;}/** * @param name * @param sex * @param age * @param students */public Teacher(String name, String sex, Integer age, List<Student> students) {super();this.name = name;this.sex = sex;this.age = age;this.students = students;}}

哈哈,這兩個對象一出來,是不是感覺很熟悉呢!對的,我們這裡封裝對象,為後面實現Java對象和XML的轉換提供很好的基礎。OK,關鍵代碼要來了哈:
/** * @Description:  * * @Title: JAXBUtil.java * @Package com.joyce.util * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午02:54:40 * @version V2.0 */package com.joyce.util;import java.io.ByteArrayOutputStream;import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;/** * @Description:JAXB對象和XML轉換util *  * @ClassName: JAXBUtil * @Copyright: Copyright (c) 2014 *  * @author Comsys-LZP * @date 2014-6-10 下午02:54:40 * @version V2.0 */public class JAXBUtil {/** * @Description: 將對象轉換為XML * * @param obj * @param beanClass * @return * @throws Exception * * @Title: JAXBUtil.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午04:23:45 * @version V2.0 */@SuppressWarnings("unchecked")public String objectToXmlStr(Object obj, Class beanClass) throws Exception {JAXBContext context = JAXBContext.newInstance(beanClass);// 根據上下文擷取marshaller對象Marshaller marshaller = context.createMarshaller();// 設定編碼字元集marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 格式化XML輸出,有分行和縮排marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 列印到控制台marshaller.marshal(obj, System.out);ByteArrayOutputStream baos = new ByteArrayOutputStream();marshaller.marshal(obj, baos);String xmlObj = new String(baos.toByteArray());return xmlObj.replace(" standalone=\"yes\"", "");}/** * @Description: 將對象轉換為XML並且寫入檔案 * * @param obj * @param beanClass * @param file * @throws Exception * * @Title: JAXBUtil.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午04:24:13 * @version V2.0 */@SuppressWarnings("unchecked")public void objectToXmlStr(Object obj, Class beanClass, File file) throws Exception {JAXBContext context = JAXBContext.newInstance(beanClass);// 根據上下文擷取marshaller對象Marshaller marshaller = context.createMarshaller();// 設定編碼字元集marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 格式化XML輸出,有分行和縮排marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 列印到控制台marshaller.marshal(obj, System.out);marshaller.marshal(obj, file);}/** * @Description: XML轉換為對象 * * @param <T> * @param file * @param beanClass * @return * @throws Exception * * @Title: JAXBUtil.java * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午04:24:50 * @version V2.0 */@SuppressWarnings("unchecked")public <T> T xmlStrToObject(File file, Class<T> beanClass) throws Exception {T bean = beanClass.newInstance();JAXBContext context = JAXBContext.newInstance(beanClass);Unmarshaller unmarshaller = context.createUnmarshaller();bean = (T) unmarshaller.unmarshal(file);return bean;}}

這其實都是Java中的基礎,沒事的時候都可以看看Java的源碼和Jdk API等等,會看到你可能想都沒有想過的東西!馬上上測試類別:
/** * @Description:  * * @Title: JAXBTest.java * @Package com.joyce.test * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午03:04:05 * @version V2.0 */package com.joyce.test;import java.io.File;import java.util.ArrayList;import java.util.List;import com.joyce.bean.Student;import com.joyce.bean.Teacher;import com.joyce.util.JAXBUtil;/** * @Description: 測試類別 * * @ClassName: JAXBTest * @Copyright: Copyright (c) 2014 * * @author Comsys-LZP * @date 2014-6-10 下午03:04:05 * @version V2.0 */public class JAXBTest {public static void main(String[] args) {try {Teacher teacher = new Teacher("JuanJuan", "女", 22);Student student = new Student("Joyce.Luo", "男", 21);Student student2 = new Student("Phang.Law", "男", 18);JAXBUtil util = new JAXBUtil();List<Student> stuList = new ArrayList<Student>();stuList.add(student);stuList.add(student2);teacher.setStudents(stuList);String xmlTeaStr = util.objectToXmlStr(teacher, Teacher.class);System.out.println("\n包含集合的對象轉換為XML:\n" + xmlTeaStr);String xmlStr = util.objectToXmlStr(student, Student.class);System.out.println("\n對象轉換為XML:\n" + xmlStr);File file = new File("str.xml");System.out.println("檔案是否存在:" + file.exists());//util.objectToXmlStr(student, Student.class, file);Student stu = util.xmlStrToObject(file, Student.class);System.out.println("\nXML轉換為對象:\n" + stu.getName() + "\t" + stu.getSex() + "\t" + stu.getAge());} catch (Exception e) {e.printStackTrace();}}}

結果展示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Teacher>    <age>22</age>    <name>JuanJuan</name>    <sex>女</sex>    <Student name="Joyce.Luo">        <age>21</age>        <sex>男</sex>    </Student>    <Student name="Phang.Law">        <age>18</age>        <sex>男</sex>    </Student></Teacher>包含集合的對象轉換為XML:<?xml version="1.0" encoding="UTF-8"?><Teacher>    <age>22</age>    <name>JuanJuan</name>    <sex>女</sex>    <Student name="Joyce.Luo">        <age>21</age>        <sex>男</sex>    </Student>    <Student name="Phang.Law">        <age>18</age>        <sex>男</sex>    </Student></Teacher><?xml version="1.0" encoding="UTF-8" standalone="yes"?><Student name="Joyce.Luo">    <age>21</age>    <sex>男</sex></Student>對象轉換為XML:<?xml version="1.0" encoding="UTF-8"?><Student name="Joyce.Luo">    <age>21</age>    <sex>男</sex></Student>檔案是否存在:trueXML轉換為對象:Joyce.Luo男21

各位有什麼好建議,歡迎提哦!完整資源: http://download.csdn.net/download/luo201227/7505479

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.