将pojo转化为XML字符串
所需要的Maven 所需要额依赖
com.thoughtworks.xstream XStream 1.4.4//将XML的字符串转化为pojo,参数为XML字符串,返回值为pojo类
XStream xStream = new XStream();
//root为根节点的名字 root类为包括所有 字段 和get方法的类
xstream.alias("Root",Root.class);
//head根节点下子节点的名字 head类为 子节点下所有节点名字的字段
xstream.alias("head", Head.class);
//参数为字符串 返回的是object泛型 一般用root类(包括所属性方法的类)
Root root =(root) xStream.fromXML("");
//将pojo转化为XML的字符串, 参数为pojo类,返回参数为XML字符串
XStream xStream1 = new XStream();
xStream1.alias("root",Root.class);
xStream1.alias("head", Head.class);
xStream1.alias("body", Body.class);
Root root = (Root) xStream1.fromXML(s1);
System.out.println(root);
全部的代码测试类
@Test
public void s1(){
Body body = new Body();
body.setNumber1(“111”);
body.setNumber2(“222”);
body.setNumber3(“333”);
Heard heard = new Heard();
heard.setCmd(“1111”);
Root pojo = new Root(heard,body);
XStream xStream = new XStream();
//改变根节点名字
xStream.alias(“root”,pojo.getClass());
//封装为xml字符串
String s1 = xStream.toXML(pojo);
System.out.println(s1);
String xml="\n" +
" <head class=“Heard”>\n" +
" 1111\n" +
" \n" +
" \n" +
" 111\n" +
" 222\n" +
" 333\n" +
" \n" +
“”;
XStream xStream1 = new XStream();
xStream1.alias(“root”,Root.class);
xStream1.alias(“head”, Head.class);
xStream1.alias(“body”, Body.class);
Root root = (Root) xStream1.fromXML(s1);
System.out.println(root);
}
对应的pojo类
//@Data注解为lombok的插件 没有插件 自己手动加上get set toString 方法
@Data
public class Root {
private Object head;
private Object body;
public Root() {
}
public Root(Object head, Object body) {
this.head = head;
this.body = body;
}
}
@Data
public class Head {
private String cmd;
}
@Data
public class Body {
private String number1;
private String number2;
private String number3;
}
上一篇: 枚举类应用