现在有xml
<boy>
<age>123</age>
<sex>男</sex>
<hobbies>
<hobby>
<a>篮球</a>
<b>足球</b>
<c>排球</c>
</hobby>
<hobby>
<a>篮球</a>
<b>足球</b>
<c>排球</c>
</hobby>
</hobbies>
</boy>
现在需要将该xml转成boy对象,代码如下
public class Boy {
private String age;
private String sex;
private List<Hobby> hobbies;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<Hobby> getHobbies() {
return hobbies;
}
public void setHobbies(List<Hobby> hobbies) {
this.hobbies = hobbies;
}
}
package domain;
public class Hobby {
private String a;
private String b;
private String c;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
package test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import domain.Boy;
import domain.Hobby;
public class XmltoObejctTest {
public static void main(String[] args) throws Exception {
StringBuffer buffer = new StringBuffer();
buffer.append("<boy>");
buffer.append("<age>123</age>");
buffer.append("<sex>男</sex>");
buffer.append("<hobbies>");
buffer.append("<hobby>");
buffer.append("<a>篮球</a>");
buffer.append("<b>足球</b>");
buffer.append("<c>排球</c>");
buffer.append("</hobby>");
buffer.append("<hobby>");
buffer.append("<a>篮球</a>");
buffer.append("<b>足球</b>");
buffer.append("<c>排球</c>");
buffer.append("</hobby>");
buffer.append("</hobbies>");
buffer.append("</boy>");
XStream xStream = new XStream(new DomDriver());
xStream.alias("boy", Boy.class);
xStream.alias("hobby", Hobby.class);
Boy boy = (Boy)xStream.fromXML(buffer.toString());
System.out.println(boy.getAge());
}
}
Java对象boy成功获得