1. 程式人生 > >JAXB的使用(java物件和xml文字的相互轉換)

JAXB的使用(java物件和xml文字的相互轉換)

JAXB(Java Architecture for XML Binding) 是一個業界的標準,是一項可以根據XML Schema產生Java類的技術。該過程中,JAXB也提供了將XML例項文件反向生成Java物件樹的方法,並能將Java物件樹的內容重新寫到XML例項文件。從另一方面來講,JAXB提供了快速而簡便的方法將XML模式繫結到Java表示,從而使得Java開發者在Java應用程式中能方便地結合XML資料和處理函式, 在JDK1.6時,JAXB 2.0是JDK 1.6的組成部分。JAXB 2.2.3是JDK 1.7的組成部分。

JDK中JAXB相關的重要Class和Interface:

  1. JAXBContext類,是應用的入口,用於管理XML/Java繫結資訊。

  2. Marshaller介面,將Java物件序列化為XML資料。

  3. Unmarshaller介面,將XML資料反序列化為Java物件。

JDK中JAXB相關的重要Annotation:

  1. @XmlType,將Java類或列舉型別對映到XML模式型別
  2. @XmlAccessorType(XmlAccessType.FIELD) ,控制欄位或屬性的序列化。FIELD表示JAXB將自動繫結Java類中的每個非靜態的(static)、非瞬態的(由@XmlTransient標註)欄位到XML。其他值還有XmlAccessType.PROPERTY和XmlAccessType.NONE。
  3. @XmlAccessorOrder,控制JAXB 繫結類中屬性和欄位的排序。
  4. @XmlJavaTypeAdapter,使用定製的介面卡(即擴充套件抽象類XmlAdapter並覆蓋marshal()和unmarshal()方法),以序列化Java類為XML。
  5. @XmlElementWrapper ,對於陣列或集合(即包含多個元素的成員變數),生成一個包裝該陣列或集合的XML元素(稱為包裝器)。
  6. @XmlRootElement,將Java類或列舉型別對映到XML元素。
  7. @XmlElement,將Java類的一個屬性對映到與屬性同名的一個XML元素。
  8. @XmlAttribute,將Java類的一個屬性對映到與屬性同名的一個XML屬性。

例項

  • 建立一個User類和一個Book類,其中User類含有一個Book類的集合屬性

User類:

package com.yaolong.jax2xml.bean;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name = "USER")  
@XmlType(propOrder={"username","age","height","hobby","books"})
public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    @XmlElement(name = "USERNAME")
    private String username;

    @XmlElement(name = "AGE")
    private String age;

    @XmlElement(name = "HEIGHT")
    private String height;

    @XmlElement(name = "HOBBY")
    private String hobby;

    @XmlElementWrapper(name = "BOOKS") 
    @XmlElement(name = "BOOK")
    private List<Book> books;

    public User() {

    }


    public User(String username, String age, String height, String hobby,List<Book> books) {
        super();
        this.username = username;
        this.age = age;
        this.height = height;
        this.hobby = hobby;
        this.books = books;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public List<Book> getBooks() {
        return books;
    }

    public void setBook(List<Book> books) {
        this.books = books;
    }


    @Override
    public String toString() {
        return "User [username=" + username + ", age=" + age + ", height="
                + height + ", hobby=" + hobby + ", books=" + books + "]";
    }

}

Book類:

package com.yaolong.jax2xml.bean;

import java.io.Serializable;

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

@XmlRootElement(name="BOOK")
@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(propOrder={"bookName","price","desc"})
public class Book implements Serializable{

    private static final long serialVersionUID = 1L;

    @XmlElement(name="DESCRIPTION")
    private String desc;

    @XmlElement(name="BOOKNAME")
    private String bookName;

    @XmlElement(name="PRICE")
    private String price;

    public Book(){

    }

    public Book(String desc, String bookName, String price) {
        super();
        this.desc = desc;
        this.bookName = bookName;
        this.price = price;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "Book [desc=" + desc + ", bookName=" + bookName + ", price="
                + price + "]";
    }

}

JaxB工具類:

package com.yaolong.jax2xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @Description:xml和物件相互轉換工具類
 * @author:yaolong
 * @data:2017年2月9日 下午10:46:57
 * @version:1.0
 */
public class JaxbUtil {

    /**
     * JavaBean轉換成xml 預設編碼UTF-8
     * 
     * @param obj
     * @param writer
     * @return
     */
    public static String convertToXml(Object obj) {
        return convertToXml(obj, "UTF-8");
    }

    /**
     * JavaBean轉換成xml
     * 
     * @param obj
     * @param encoding
     * @return
     */
    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);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml頭資訊 
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * xml轉換成JavaBean
     * @param xml
     * @param c
     * @return
     * @throws JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c)
            throws JAXBException {
        T t = null;
        JAXBContext context = JAXBContext.newInstance(c);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        t = (T) unmarshaller.unmarshal(new StringReader(xml));
        return t;
    }
}

測試類:

package com.yaolong.jax2xml;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBException;

import com.yaolong.jax2xml.bean.Book;
import com.yaolong.jax2xml.bean.User;

public class JaxbeanTest {

    public static void main(String[] args) throws JAXBException {
        //準備資料
        Book book1 = new Book("葵花寶典","100元","欲練此功,必須自宮");
        Book book2 = new Book("辟邪劍譜","120元","不用自宮也能練");
        Book book3 = new Book("九陰真經","130元","練完此功,天下無敵");
        List<Book> books = new ArrayList<Book>();
        books.add(book1);
        books.add(book2);
        books.add(book3);
        User user = new User("吳渣渣","23","170","睡覺",books);
        //將物件轉化成xml文字
        String xmlStr = JaxbUtil.convertToXml(user, "UTF-8");
        System.out.println(xmlStr);

        System.out.println("===================================================================================================");

        //xml文字轉換成物件
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                + "<USER>"
                    + "<USERNAME>吳渣渣</USERNAME>"
                    + "<AGE>23</AGE>"
                    + "<HEIGHT>170</HEIGHT>"
                    + "<HOBBY>睡覺</HOBBY>"
                    + "<BOOKS>"
                        + "<BOOK>"
                        + "<BOOKNAME>100元</BOOKNAME>"
                        + "<PRICE>欲練此功,必須自宮</PRICE>"
                        + "<DESCRIPTION>葵花寶典</DESCRIPTION>"
                        + "</BOOK>"
                        + "<BOOK>"
                        + "<BOOKNAME>120元</BOOKNAME>"
                        + "<PRICE>不用自宮也能練</PRICE>"
                        + "<DESCRIPTION>辟邪劍譜</DESCRIPTION>"
                        + "</BOOK>"
                        + "<BOOK>"
                        + "<BOOKNAME>130元</BOOKNAME>"
                        + "<PRICE>練完此功,天下無敵</PRICE>"
                        + "<DESCRIPTION>九陰真經</DESCRIPTION>"
                        + "</BOOK>"
                    + "</BOOKS>"
                + "</USER>";

        User userBean = JaxbUtil.converyToJavaBean(xml, User.class);
        System.err.println(userBean);

    }

}

列印結果: