1. 程式人生 > >java物件與XML互轉

java物件與XML互轉

1. 定義XML對應的java實體類(可巢狀)

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;


@XmlRootElement(name="INFO") //設定生成的xml的根節點的名稱
@XmlAccessorType(XmlAccessType.FIELD)  //設定根據欄位還是方法生成
public class InfoIN implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = -7060974820353568568L;

    //函式名
    @XmlElement(name="FUNNAM")
    private String FUNNAM;
    
    //資料格式
    @XmlElement(name="DATTYP")
    private int DATTYP;
    
    //登陸使用者名稱
    @XmlElement(name="LGNNAM")
    private String LGNNAM;

    public String getFUNNAM() {
        return FUNNAM;
    }

    public void setFUNNAM(String fUNNAM) {
        FUNNAM = fUNNAM;
    }

    public int getDATTYP() {
        return DATTYP;
    }

    public void setDATTYP(int dATTYP) {
        DATTYP = dATTYP;
    }

    public String getLGNNAM() {
        return LGNNAM;
    }

    public void setLGNNAM(String lGNNAM) {
        LGNNAM = lGNNAM;
    }
}

2. 呼叫定義好的轉換工具類

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

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.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

/**
 * XML  物件互轉工具類
 * 使用Jaxb2.0實現XML<->Java Object的Mapper.
 * 在建立時需要設定所有需要序列化的Root物件的Class.
 * 特別支援Root物件是Collection的情形.
 */
public class JaxbUtil {

    @SuppressWarnings("rawtypes")
    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

    /**
     * Java Object->Xml without encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root) {
        Class clazz = root.getClass();
        return toXml(root, clazz, null);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, String encoding) {
        Class clazz = root.getClass();
        return toXml(root, clazz, encoding);
    }

    /**
     * Java Object->Xml with encoding.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Object root, Class clazz, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
           e.printStackTrace();
           return null;
        }
    }

    /**
     * Java Collection->Xml without encoding, 特別支援Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection<?> root, String rootName, Class clazz) {
        return toXml(root, rootName, clazz, null);
    }

    /**
     * Java Collection->Xml with encoding, 特別支援Root Element是Collection的情形.
     */
    @SuppressWarnings("rawtypes")
    public static String toXml(Collection<?> root, String rootName, Class clazz, 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(clazz, encoding).marshal(wrapperElement, writer);

            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 建立Marshaller並設定encoding(可為null).
     * 執行緒不安全,需要每次建立或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Marshaller createMarshaller(Class clazz, String encoding) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);

            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) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 建立UnMarshaller.
     * 執行緒不安全,需要每次建立或pooling。
     */
    @SuppressWarnings("rawtypes")
    public static Unmarshaller createUnmarshaller(Class clazz) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    @SuppressWarnings("rawtypes")
    protected static JAXBContext getJaxbContext(Class clazz) {
        Validate.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
                throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
                        + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

    /**
     * 封裝Root Element 是 Collection的情況.
     */
    public static class CollectionWrapper {

        @XmlAnyElement
        protected Collection<?> collection;
    }
}