1. java程序中使用xstream方法將實體類轉成xml,實體類中有null值,生成的xml就去除了含有null值的節點!
XStream 用法詳解 java 類與 XML 互換
現在 WEB數據交換的時代,傳送XML目前是一個比較流行的方式,具有統一的規則約束,為實現後台介面提供了一個很方便的實現。
我編寫了一個 接收XML並轉換成所需要的Object類的 小例子,希望能夠對做互聯網數據傳輸、介面調用的朋友有所幫助。
首先要導入jar包xstream-1.4.3-sources.jar 和 xmlpull-1.1.3.1.jar 兩個包;
其次是預備一個 XML 事例
[html] view plain
<config>
<span style="white-space:pre"> </span><client type="8888" osversion="9999" version="123" oemtag="5555" area="areacode"/>
<span style="white-space:pre"> </span><protocol>1.10</protocol>
<span style="white-space:pre"> </span><sign value="asdfasdf"/>
<span style="white-space:pre"> </span><vientiance version="version"/>
</config>
其次 就是 按照 XML節點的順序 從外 到內 編寫 java PO類,此實例的目的是將上面的XML轉換為 AllnewstateRQ 這個實體類,然後從裡面列印出測試數據。
下面依次是 config節點 對應的 AllnewstateRQ類 ; client 節點 對應的 Client 類;sign 節點對應的 Sign類;vientiance 節點 對應的 Vientiance類。
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("config")
public class AllnewstateRQ {
//當節點下有獨立屬性的時候,需要創建一個獨立的類用來保存節點內的屬性
private Client client = new Client();
private Sign sign = new Sign();
private Vientiance vientiance = new Vientiance();
//當節點下沒有屬性,直接由StringValue的時候可直接創建String類型屬性
private String protocol;
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Sign getSign() {
return sign;
}
public void setSign(Sign sign) {
this.sign = sign;
}
public Vientiance getVientiance() {
return vientiance;
}
public void setVientiance(Vientiance vientiance) {
this.vientiance = vientiance;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("client")
public class Client {
@XStreamAsAttribute //對屬性值進行註解
private String type;//此時類中的屬性名要和xml內的屬性名相對應
@XStreamAsAttribute
private String osversion;
@XStreamAsAttribute
private String version;
@XStreamAsAttribute
private String oemtag;
@XStreamAsAttribute
private String area;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOsversion() {
return osversion;
}
public void setOsversion(String osversion) {
this.osversion = osversion;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getOemtag() {
return oemtag;
}
public void setOemtag(String oemtag) {
this.oemtag = oemtag;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("sign") //此處要對應節點的名稱
public class Sign {
@XStreamAsAttribute
private String value;//此處對應節點內屬性名稱
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("vientiance")
public class Vientiance {
@XStreamAsAttribute
private String version;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
測試main方法
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class TestStream {
public static void main(String[] args) {
String reqXml = getXml();
XStream xs = new XStream(new DomDriver());
xs.processAnnotations(new Class[]{AllnewstateRQ.class,Client.class,Sign.class,Vientiance.class});
Object obj = xs.fromXML(reqXml);
AllnewstateRQ allnewstateRQ = (AllnewstateRQ) obj;
System.out.println(allnewstateRQ.getProtocol());
System.out.println(allnewstateRQ.getClient().getArea());
System.out.println(reqXml);
}
static String getXml(){
StringBuilder str = new StringBuilder();
str.append("")
.append("<config>")
.append("<client type=\"8888\" osversion=\"9999\" version=\"123\" oemtag=\"5555\" area=\"areacode\" />")
.append("<protocol>1.10</protocol>")
.append("<sign value=\"asdfasdf\" />")
.append("<vientiance version=\"version\" />")
.append("</config>")
;
return str.toString();
}
}
輸出結果:
[java] view plain
1.10
areacode
<config><client type="8888" osversion="9999" version="123" oemtag="5555" area="areacode" /><protocol>1.10</protocol><sign value="asdfasdf" /><vientiance version="version" /></config>
2. 用XStream 轉換java對象成xml的一個疑問
3. java用XStream把xml轉換成javabean的問題
xStream可以輕易的將Java對象和xml文檔相互轉換,而且可以修改某個特定的屬性和節點名稱,而且也支持json的轉換;它們都完美支持JSON,但是對xml的支持還不是很好。一定程度上限制了對Java對象的描述,不能讓xml完全體現到對Java對象的描述。這里將會介紹xStream對JSON、XML的完美支持。xStream不僅對XML的轉換非常友好,而且提供annotation註解,可以在JavaBean中完成對xml節點、屬性的描述。以及對JSON也支持,只需要提供相關的JSONDriver就可以完成轉換。
4. java通過xstream解析xml,這樣的節點bean對象應該如何創建
用 xstream 生成一個.xml 你就知道了。
5. xStream轉換xml同名節點到java對象問題
假設XML文件(config/0_student.xml)內容如下:
<students>
<student>
<name>zhang3</name>
<age>20</age>
</student>
<student>
<name>li4</name>
<age>21</age>
</student>
</students>
XStream轉換代碼如下:
{
publicvoidtestToObject()throwsException{
XStreamxstream=newXStream(newDomDriver());
Filefile=newFile(XStreamUtil.class.getClassLoader().getResource("").getPath(),"config/0_student.xml");
xstream.alias("students",List.class);
xstream.alias("student",Student.class);
List<Student>students=(List<Student>)xstream.fromXML(newFileInputStream(file));
assertEquals(2,students.size());
assertEquals("zhang3",students.get(0).getName());
assertEquals("li4",students.get(1).getName());
assertEquals(20,students.get(0).getAge());
assertEquals(21,students.get(1).getAge());
}
}
6. xstream xml轉化成java對象
注意事項:
創建接收轉換的實體類 裡面欄位 與 xml節點一一對應。spring 使用@XStreamAlias("節點") 進行關聯。屬性名與節點一一對應是很重要的!!!不然 不能正常轉換。使用了註解以後,xml節點跟類的屬性名不再有關系,但是 註解裡面使用的名字就默認是與xml節點對應的。所以保持@XStreamAlias("節點") 裡面節點的值與xml 一一對應。
xstream.processAnnotations(需要轉化的實體類.class);
實體類 例子:
package com.cmsz.cmup.alipay.model.responses;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
/**
* @Title: AccountResultVO.java
* @Package com.cmsz.cmup.alipay.vo.result
* @Description: alipay返回xml字元串封裝對象
* @author yekun
* @date 2015年12月4日 上午10:50:23
*/
@XStreamAlias("alipay")
public class AccountResponseModel {
/** 錯誤信息 */
@XStreamAlias("error")
private String error;
/** 請求是否成功 */
@XStreamAlias("is_success")
private String isSuccess;
/** 請求參數 */
@XStreamAlias("request")
private Request request;
/** xml節點 */
@XStreamAlias("response")
private Response response;
/** 簽名 */
@XStreamAlias("sign")
private String sign;
/** 簽名加密方式 */
@XStreamAlias("sign_type")
private String sign_type;
//轉換代碼
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(實體類.class);
xstream.fromXML(xmlStr);//xml格式的字元串
7. jsp Form->Java Bean ->使用XStream->生成XML文件
[代碼]1.實體類:PersonBean
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("person")
public class PersonBean {
@XStreamAlias("firstName")
private String firstName;
@XStreamAlias("lastName")
private String lastName;
@XStreamAlias("telphone")
private PhoneNumber tel;
@XStreamAlias("faxphone")
private PhoneNumber fax;
//省略setter和getter }
main函數示例1:toxml
import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JsonWriter.Format; import com.thoughtworks.xstream.io.xml.DomDriver;
public class PersonTest {
public static void main(String[] args) {
PersonBean per=new PersonBean();
per.setFirstName("chen");
per.setLastName("youlong");
PhoneNumber tel=new PhoneNumber();
tel.setCode(137280);
tel.setNumber("137280968");
PhoneNumber fax=new PhoneNumber();
fax.setCode(20);
fax.setNumber("020221327");
per.setTel(tel);
per.setFax(fax);
//java對象轉換成xml
String xml=XmlUtil.toXml(per);
System.out.println("xml==="+xml);
}
}
main函數示例2:toBean
public static void main(String[] args) {
String xmlStr="<person>"+
"<firstName>chen</firstName>"+
"<lastName>youlong</lastName>"+
"<telphone>"+
"<code>137280</code>"+
"<number>137280968</number>"+
"</telphone>"+
"<faxphone>"+
"<code>20</code>"+
"<number>020221327</number>"+
"</faxphone>"+
"<friends>"+
"<name>A1</name>"+
"<name>A2</name>"+
"<name>A3</name>"+
"</friends>"+
"<pets>"+
"<pet>"+
"<name>doly</name>"+
"<age>2</age>"+
"</pet>"+
"<pet>"+
"<name>Ketty</name>"+
"<age>2</age>"+
"</pet>"+
"</pets>"+
"</person>"; //用泛型的知識
PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
System.out.println("person=firstname=="+person.getFirstName());
System.out.println("person==Friends==name1=="+person.getFriend().getName().get(0));
System.out.println("person==Pets==name2=="+person.getPet().getAnimalList().get(1).getName());
}
8. XStream將java對象轉換為xml時,對象欄位中的下劃線「_」,轉換後變成了兩個
warning: [deprecation] XppDriver(com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer) in com.thoughtworks.xstream.io.xml.XppDriver has been deprecated
已經過時的方法,所以,不會調用此方法。