1. 程式人生 > >jaxb實現xml與bean的相互轉化

jaxb實現xml與bean的相互轉化

jaxb使用說明

  這裡邊有提到MessageFormat,可以瞭解下。下邊還有一個其他部落格粘過來的幾行程式碼,記錄一下。

 這裡以《書》為例,寫一個完整的測試程式碼,xml包含了各種元素和集合。

 test.xml

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<book id="1234567890" name="尋醫不如自醫">
    <author>陳金柱</author>
    <press>金城出版社</press>
    <main_info>
        <chapters_num>5</chapters_num>
        <editor>王景濤</editor>
        <pub_time>2017-01-01</pub_time>
    </main_info>
    <chapters>
        <chapter>
            <num>1</num>
            <name>你所不知道的事</name>
        </chapter>
        <chapter>
            <num>2</num>
            <name>人體中有哪些重要的部分</name>
        </chapter>
        <chapter>
            <num>3</num>
            <name>中醫健康基礎知識</name>
        </chapter>
    </chapters>
</book>

 實體類:

import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType; /** * 書 * 不指定順序的時候是按英文字母排序的 * propOrder指定順序,裡邊填的是屬性的名,不是註解裡的name * 如果指定順序的話,需要把所有屬性都寫裡邊,不然會報錯 * @author changxinzhi * */ @XmlRootElement(name = "book") @XmlType(propOrder={"id","name","author","press","mainInfo","chapters"}) public class Book { private String id;//圖書ID private String name;//圖書名稱 private String author;//作者 private String press;//出版社 private MainInfo mainInfo;//重要資訊 private List<Chapter> chapters;//章節資訊  @XmlAttribute(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlAttribute(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name = "author") public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @XmlElement(name = "press") public String getPress() { return press; } public void setPress(String press) { this.press = press; } @XmlElement(name = "main_info") public MainInfo getMainInfo() { return mainInfo; } public void setMainInfo(MainInfo mainInfo) { this.mainInfo = mainInfo; } @XmlElementWrapper(name = "chapters") @XmlElement(name = "chapter") public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } }
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 書的重要資訊
 * @author cxz
 */
@XmlRootElement(name = "main_info")
public class MainInfo {
    private String editor;//責任編輯
    private String pub_time;
    private String chapters_num; public String getEditor() { return editor; } public void setEditor(String editor) { this.editor = editor; } public String getPub_time() { return pub_time; } public void setPub_time(String pub_time) { this.pub_time = pub_time; } public String getChapters_num() { return chapters_num; } public void setChapters_num(String chapters_num) { this.chapters_num = chapters_num; } }
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
* 章節資訊
* @author cxz
*/
@XmlRootElement(name="chapter")
@XmlType(propOrder={"num","name"})
public class Chapter { private String num; private String name; public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

工具類

import java.io.StringReader;
import java.io.StringWriter;
import java.text.MessageFormat;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * json使用alibaba.fastjson * @author cxz * Jaxb2.0 處理Xml與Object轉換 */ public class JaxbObjectAndXmlUtil { /** * 此處使用了Stringreader,其實Unmarshaller介面還支援 * File,InputStream,URL,StringBuffer,org.w3c.dom.Node等反序列化 * API連線 * http://tool.oschina.net/uploads/apidocs/jdk-zh/javax/xml/bind/Unmarshaller.html * @param xmlStr 字串 * @param c 物件Class型別 * @return 物件例項 */ @SuppressWarnings({ "unchecked", "finally" }) public static <T> T xml2Object(String xmlStr,Class<T> c){ try{ JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr)); return t; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * 可變引數 * config裡使用佔位符 {0} {1} {2},單引號要使用兩個
* MessageFormat使用連結 * @param config * @param c * @param arguments * @return */ @SuppressWarnings("unchecked") public static <T> T xml2Object(String config,Class<T> c,Object... arguments){ try{ if (arguments.length > 0) { config = MessageFormat.format(config, arguments); } JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new StringReader(config)); return t; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * @param object 物件 * @return 返回xmlStr */ public static String object2Xml(Object object){ try{ StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshal = context.createMarshaller(); marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化輸出 marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 編碼格式,預設為utf-8 marshal.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml頭資訊 marshal.setProperty("jaxb.encoding", "utf-8"); marshal.marshal(object,writer); return new String(writer.getBuffer()); }catch(Exception e){ e.printStackTrace(); return null; } } }

測試類

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

import com.alibaba.fastjson.JSON;

public class test {
     /**
     * 測試方法
     * @param args
     */
    public static void main(String[] args){
        //建立內容
        MainInfo mainInfo = new MainInfo(); mainInfo.setEditor("王景濤"); mainInfo.setPub_time("2017-01-01"); mainInfo.setChapters_num("5"); Chapter chapter1 = new Chapter(); chapter1.setNum("1"); chapter1.setName("你所不知道的事"); Chapter chapter2 = new Chapter(); chapter2.setNum("2"); chapter2.setName("人體中有哪些重要的部分"); Chapter chapter3 = new Chapter(); chapter3.setNum("3"); chapter3.setName("中醫健康基礎知識"); Book book = new Book(); List<Chapter> chapters = new ArrayList<Chapter>(); chapters.add(chapter1); chapters.add(chapter2); chapters.add(chapter3); book.setChapters(chapters); book.setMainInfo(mainInfo); book.setId("1234567890"); book.setName("尋醫不如自醫"); book.setAuthor("陳金柱"); book.setPress("金城出版社"); String xmlStr = JaxbObjectAndXmlUtil.object2Xml(book);//構造報文 XML 格式的字串 System.out.println("物件轉xml報文: \n"+xmlStr); Book book2 = JaxbObjectAndXmlUtil.xml2Object(xmlStr, Book.class); System.out.println("報文轉xml轉: \n"+JSON.toJSONString(book2)); } }

 到這裡已寫完。

粘過來的幾行程式碼,歡迎留言討論。

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;

/**
 * 使用Jaxb2.0實現XML<->Java Object的Binder.
 * StringUtils依賴commons-long包
 * 特別支援Root物件是List的情形.---??? ‘xml規範就是有且只有一個根元素’--不甚理解這裡的做法
 * @author
 */
public class JaxbUtil {
    // 多執行緒安全的Context.
    private JAXBContext jaxbContext;
 
    /**
     * @param types  所有需要序列化的Root物件的型別.
     */
    public JaxbUtil(Class<?>... types) {
        try {
            jaxbContext = JAXBContext.newInstance(types);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Java Object->Xml.
     */
    public String toXml(Object root, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Java Object->Xml, 特別支援對Root Element是Collection的情形.
     */
    @SuppressWarnings("unchecked")
    public String toXml(Collection root, String rootName, String encoding) {
        try {
            CollectionWrapper wrapper = new CollectionWrapper();
            wrapper.collection = root;
 
            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(
                    new QName(rootName), CollectionWrapper.class, wrapper);
 
            StringWriter writer = new StringWriter();
            createMarshaller(encoding).marshal(wrapperElement, writer);
 
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public <T> T fromXml(String xml) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * Xml->Java Object, 支援大小寫敏感或不敏感.
     */
    @SuppressWarnings("unchecked")
    public <T> T fromXml(String xml, boolean caseSensitive) {
        try {
            String fromXml = xml;
            if (!caseSensitive)
                fromXml = xml.toLowerCase();
            StringReader reader = new StringReader(fromXml);
            return (T) createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 建立Marshaller, 設定encoding(可為Null).
     */
    public Marshaller createMarshaller(String encoding) {
        try {
            Marshaller marshaller = jaxbContext.createMarshaller();
 
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
 
            if (StringUtils.isNotBlank(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }
            return marshaller;
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 建立UnMarshaller.
     */
    public Unmarshaller createUnmarshaller() {
        try {
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 封裝Root Element 是 Collection的情況.
* xmlAnyType查到的東西不多,不太懂這個。
*/ public static class CollectionWrapper { @SuppressWarnings("unchecked") @XmlAnyElement protected Collection collection; } }

測試方法片段

        //寫不寫CollectionWrapper.class有什麼區別,都可以正常執行
        //將java物件轉換為XML字串
        JaxbUtil requestBinder = new JaxbUtil(Hotel.class,CollectionWrapper.class);
        String retXml = requestBinder.toXml(hotel, "utf-8");
        System.out.println("xml:"+retXml);
        
        //將xml字串轉換為java物件
        JaxbUtil resultBinder = new JaxbUtil(Hotel.class,CollectionWrapper.class);
        Hotel hotelObj = resultBinder.fromXml(retXml);