Java對象和XML相互轉換

 JAXB XML工具類java

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;

/** 
 * 使用Jaxb2.0實現XML<->Java Object的Binder. 
 *  
 * 特別支持Root對象是List的情形. 
 *  
 * @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 (null!=encoding && !encoding.isEmpty()) {  
                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的狀況. 
     */  
    public static class CollectionWrapper {  
        @SuppressWarnings("unchecked")  
        @XmlAnyElement  
        protected Collection collection;  
    }  
}

測試對象A安全

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

//節點循序
@XmlType(propOrder = {"aa","ab","ac","ad"})
@XmlRootElement(name="XMLOBJA")
public class XmlObja {
     
	private String aa;
	
	private String ab;
	
	private String ac;
	
	private XmlObjb ad;

	//轉換接口Name
	@XmlElement(name = "AA") 
	public String getAa() {
		return aa;
	}

	public void setAa(String aa) {
		this.aa = aa;
	}

	
	@XmlAttribute 
	public String getAb() {
		return ab;
	}

	public void setAb(String ab) {
		this.ab = ab;
	}

	public String getAc() {
		return ac;
	}

	public void setAc(String ac) {
		this.ac = ac;
	}
	@XmlElement(name = "AD") 
	public XmlObjb getAd() {
		return ad;
	}

	public void setAd(XmlObjb ad) {
		this.ad = ad;
	}
}

測試對象B 多線程

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class XmlObjb {
    
	private String ba;
	
	private String bb;
	
	private String bc;

	public String getBa() {
		return ba;
	}

	public void setBa(String ba) {
		this.ba = ba;
	}

	public String getBb() {
		return bb;
	}

	public void setBb(String bb) {
		this.bb = bb;
	}

	public String getBc() {
		return bc;
	}

	public void setBc(String bc) {
		this.bc = bc;
	}
	
	
}

測試 app

public class XmlTest {
	public static void main(String[] args) {
		XmlObja xmlObja = new XmlObja();
		xmlObja.setAa("中文");
		xmlObja.setAb("a2");
		xmlObja.setAc("a3");
		XmlObjb xmlObjb = new XmlObjb();
		xmlObjb.setBa("b1");
		xmlObjb.setBb("b2");
		xmlObjb.setBc("b3");
		xmlObja.setAd(xmlObjb);
		JaxbUtil requestBinder = new JaxbUtil(XmlObja.class); 
		//對象轉XML
		String xml = requestBinder.toXml(xmlObja, "GBK");
		System.out.println("-----------Obj to xml-----------");
		System.out.println(xml);
		System.out.println("-----------xml to Obj-----------");
		//XML轉對象
		XmlObja	xmlObj =(XmlObja) requestBinder.fromXml(xml);
		System.out.println(xmlObj);
	}
}

結果 工具

-----------Obj to xml-----------
<?xml version="1.0" encoding="GBK" standalone="yes"?>
<XMLOBJA ab="a2">
    <AA>中文</AA>
    <ac>a3</ac>
    <AD>
        <ba>b1</ba>
        <bb>b2</bb>
        <bc>b3</bc>
    </AD>
</XMLOBJA>

-----------xml to Obj-----------
com.test.bean.XmlObja@1a61172
相關文章
相關標籤/搜索