對象和XML相互轉換

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

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;
}

}this

import javax.xml.bind.annotation.XmlRootElement;code

@XmlRootElement public class XmlObjb {xml

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;
}

}對象

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-----------get

<?xml version="1.0" encoding="GBK" standalone="yes"?>io

<XMLOBJA ab="a2"> <AA>中文</AA> <ac>a3</ac> <AD> <ba>b1</ba> <bb>b2</bb> <bc>b3</bc> </AD> </XMLOBJA>class

-----------xml to Obj----------- com.test.bean.XmlObja@1a61172test

相關文章
相關標籤/搜索