xstreamシーケンスと逆シーケンス学習
2049 ワード
XStreamシーケンスと逆シーケンス学習:
1、逆シーケンス
@XStreamAlias("USER")
public class User {
@XStreamAlias("NAME")
private String name;
@XStreamAlias("AGE")
private int age;
@XStreamAlias("SEX")
private String sex;
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
public class Test {
public static void main(String[] args) {
String xmlStr = "<USER><NAME>April</NAME><AGE>22</AGE><SEX> </SEX></USER>";
XStream xstream = new XStream(new DomDriver());
xstream.autodetectAnnotations(true);
xstream.alias("USER", User.class);
User user = (User)xstream.fromXML(xmlStr,new User());
System.out.println(" User :"+user.getName()+"---"+user.getAge()+"----"+user.getSex());
}
}
結果:逆シーケンス化後のUser情報:April---22----女
2、シーケンス化
public class Test2 {
public static void main(String[] args) {
User user = new User();
user.setName("Amy");
user.setAge(21);
user.setSex(" ");
XStream xstream = new XStream(new DomDriver());
xstream.autodetectAnnotations(true);
String xml = xstream.toXML(user);
StringBuffer xmlStr = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xmlStr.append(xml);
System.out.println(xmlStr);
}
}
必要なjarパッケージは、次のとおりです.