1. 程式人生 > >XStream 工具類 [ XmlUtil ]

XStream 工具類 [ XmlUtil ]


pom.xml


<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.10</version>
</dependency>


XmlUtil.java


package com.app.core.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

public class XmlUtil {
    /**
     * 轉換不帶CDDATA的XML
     *
     * @return
     * @
     */
    private static XStream getXStream() {
        // 例項化XStream基本物件
        XStream xstream = new XStream(new DomDriver(StandardCharsets.UTF_8.name(), new NoNameCoder() {
            // 不對特殊字元進行轉換,避免出現重新命名欄位時的“雙下劃線”
            public String encodeNode(String name) {
                return name;
            }
        }));
        // 忽視XML與JAVABEAN轉換時,XML中的欄位在JAVABEAN中不存在的部分
        xstream.ignoreUnknownElements();
        return xstream;
    }

    /**
     * 轉換帶CDDATA的XML
     *
     * @return
     * @
     */
    private static XStream getXStreamWithCData() {
        // 例項化XStream擴充套件物件
        XStream xstream = new XStream(new XppDriver() {
            // 擴充套件xstream,使其支援CDATA塊
            public HierarchicalStreamWriter createWriter(Writer out) {
                return new PrettyPrintWriter(out) {
                    // 不對特殊字元進行轉換,避免出現重新命名欄位時的“雙下劃線”
                    public String encodeNode(String name) {
                        return name;
                    }

                    // 對所有xml節點的轉換都增加CDATA標記
                    protected void writeText(QuickWriter writer, String text) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    }
                };
            }
        });
        // 忽視XML與JAVABEAN轉換時,XML中的欄位在JAVABEAN中不存在的部分
        xstream.ignoreUnknownElements();
        return xstream;
    }

    /**
     * 以壓縮的方式輸出XML
     *
     * @param obj
     * @return
     */
    public static String toCompressXml(Object obj) {
        XStream xstream = getXStream();
        StringWriter sw = new StringWriter();
        // 識別obj類中的註解
        xstream.processAnnotations(obj.getClass());
        // 設定JavaBean的類別名
        xstream.aliasType("xml", obj.getClass());
        xstream.marshal(obj, new CompactWriter(sw));
        return sw.toString();
    }

    /**
     * 以格式化的方式輸出XML
     *
     * @param obj
     * @return
     */
    public static String toXml(Object obj) {
        XStream xstream = getXStream();
        // 識別obj類中的註解
        xstream.processAnnotations(obj.getClass());
        // 設定JavaBean的類別名
        xstream.aliasType("xml", obj.getClass());
        return xstream.toXML(obj);
    }

    /**
     * 轉換成JavaBean
     *
     * @param xmlStr
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBean(String xmlStr, Class<T> cls) {
        XStream xstream = getXStream();
        // 識別cls類中的註解
        xstream.processAnnotations(cls);
        // 設定JavaBean的類別名
        xstream.aliasType("xml", cls);
        T t = (T) xstream.fromXML(xmlStr);
        return t;
    }

    /**
     * 以格式化的方式輸出XML
     *
     * @param obj
     * @return
     */
    public static String toXmlWithCData(Object obj) {
        XStream xstream = getXStreamWithCData();
        // 識別obj類中的註解
        xstream.processAnnotations(obj.getClass());
        // 設定JavaBean的類別名
        xstream.aliasType("xml", obj.getClass());
        return xstream.toXML(obj);
    }

    /**
     * 轉換成JavaBean
     *
     * @param xmlStr
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBeanWithCData(String xmlStr, Class<T> cls) {
        XStream xstream = getXStreamWithCData();
        // 識別cls類中的註解
        xstream.processAnnotations(cls);
        // 設定JavaBean的類別名
        xstream.alias("xml", cls);
        T t = (T) xstream.fromXML(xmlStr);
        return t;
    }
}