XStream xml與物件的相互轉化
jar包的依賴:
* 核心JAR包:xstream-1.4.7.jar
* 必須依賴包:xpp3_min-1.1.4c
1.將物件轉化為xml
1.1編寫類:
class Person implements Serializable {
private String name ;
private Integer age;
private String gender;
private Address add;
private List<Address> address;
//此處省略get set方法
}
class Address implements Serializable {
private String province;
private String city;
private String area;
//此處省略get set方法
}
1.2 測試程式碼
1.2.1構造資料
Person p = new Person();
p.setAge(12);
p.setGender("男");
p.setName("張三");
List<Address> list = new ArrayList<Address>();
Address address1 = new Address();
address1.setArea("犀浦鎮");
address1.setCity("成都市");
address1.setProvince("四川省");
Address address2 = new Address();
address2.setArea("紅光鎮");
address2.setCity("成都市");
address2.setProvince("四川省");
list.add(address1);
list.add(address2);
p.setAddress(list);
1.2.2使用XStream 將物件轉化為xml
XStream xStream = new XStream();
xStream.alias("person", Person.class);
xStream.alias("address", Address.class);
String xml = xStream.toXML(p);//將物件轉化為xml
System.out.println(xml);
1.3 結果輸出
<person>
<name>張三</name>
<age>12</age>
<gender>男</gender>
<address>
<address>
<province>四川省</province>
<city>成都市</city>
<area>犀浦鎮</area>
</address>
<address>
<province>四川省</province>
<city>成都市</city>
<area>紅光鎮</area>
</address>
</address>
</person>
其中多出了<address> 可以使用xStream.addImplicitCollection(Person.class,"address")方法去除
列印結果為:
<person>
<name>張三</name>
<age>12</age>
<gender>男</gender>
<address>
<province>四川省</province>
<city>成都市</city>
<area>犀浦鎮</area>
</address>
<address>
<province>四川省</province>
<city>成都市</city>
<area>紅光鎮</area>
</address>
</person>
2.將xml轉化為物件
1.xml字串:
<person>
<name>張三</name>
<age>12</age>
<gender>男</gender>
<address>
<province>四川省</province>
<city>成都市</city>
<area>犀浦鎮</area>
</address>
<address>
<province>四川省</province>
<city>成都市</city>
<area>紅光鎮</area>
</address>
</person>
2.使用XStream將xml轉化為物件
XStream xStream = new XStream();
xStream.alias("person", Person.class);
xStream.alias("address", Address.class);
xStream.addImplicitCollection(Person.class,"address");
Person person = (Person) xStream.fromXML(xml);//將xml轉化為物件