使用XStream来映射xml中列表元素到java对象
网上很多讲述使用XStream来映射xml文件到java对象的文章,但是几乎没有一篇文章讲述,如何使用XStream来映射xml中的同级的列表元素到java对象的文章。本文示例中将使用XStream 1.3.1。请去XStream的官方站点上下载相应的包。
在Eclipse中新建一个Java Project,然后引入XStream的包:xstream-1.3.1.jar和xpp3-min-1.1.4c.jar。在这里使用xpp的xml解析技术来解析xml,而不是传统的DOM或者sax来进行xml的解析。
在src下新建sample.xml文件。代码如下:
<?xml version="1.0" encoding="UTF-8"?><person id="1" name="sample"><wife name="wife_name" age="25"></wife><house name="house1" address="address1"></house> <house name="house1" address="address1"></house> <house name="house1" address="address1"></house> <house name="house1" address="address1"></house> </person>
public class House {private String name = "";private String address = "";public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}
public class Wife {private String name = "";private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
import java.util.List;public class Person {private int id;private String name;private Wife wife;private List<House> houseList;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}public List<House> getHouseList() {return houseList;}public void setHouseList(List<House> houseList) {this.houseList = houseList;}}
XStream xstream = new XStream();
xstream.alias("person", Person.class);xstream.aliasAttribute(Person.class, "id", "id");xstream.aliasAttribute(Person.class, "name", "name");xstream.alias("wife", Wife.class);xstream.aliasAttribute(Wife.class, "name", "name");xstream.addImplicitCollection(Person.class, "houseList");xstream.alias("house", House.class);xstream.aliasAttribute(House.class,"name", "name");xstream.aliasAttribute(House.class, "address", "address");
<houseList><house name="house1" address="address1"></house> <house name="house1" address="address1"></house> <house name="house1" address="address1"></house> <house name="house1" address="address1"></house> </houseList>。
Person person = (Person)xstream.fromXML(TestMain.class.getClassLoader().getResourceAsStream("sample.xml"));
System.out.println("[person.name=" + person.getName() + "]");System.out.println("[wife.name=" + person.getWife().getName() + ", wife.age=" + person.getWife().getAge() + "]");System.out.println("[person.houseList.size=" + person.getHouseList().size() + "]");System.out.println("[person.houseList.house1.name=" + person.getHouseList().get(0).getName() + ",address=" + person.getHouseList().get(0).getAddress() +"]");