通常使用xStream工具. 将集合,数组,对象转成XML.
导入两个包:
xpp3_min-1.1.4c.jar
xstream-1.4.4.jar
自定义一个类
package com.baidu;public class User { private int id; private String name; 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; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
测试类
package com.baidu;import java.util.ArrayList;import com.thoughtworks.xstream.XStream;public class Demo { public static void main(String[] args) { User u=new User(); u.setId(11); u.setName("风清扬"); User u1=new User(); u1.setId(12); u1.setName("小师妹"); ArrayListarray=new ArrayList (); array.add(u); array.add(u1); //创建XStream对象 XStream xs=new XStream(); //使用XStream对象转换对象 String xml = xs.toXML(array); //输出转换的 System.out.println(xml); }}
输出结果:
//表示类的全路径 11 //类的属性风清扬 //类的属性12 小师妹
让属性标签变为类标签的属性(内包含)
package com.baidu;import java.util.ArrayList;import com.thoughtworks.xstream.XStream;public class Demo { public static void main(String[] args) { User u=new User(); u.setId(11); u.setName("风清扬"); User u1=new User(); u1.setId(12); u1.setName("小师妹"); ArrayListarray=new ArrayList (); array.add(u); array.add(u1); //将集合转换为xml XStream xs=new XStream(); //将类中的属性作为类的标签的内部属性 xs.useAttributeFor(User.class, "id"); xs.useAttributeFor(User.class,"name"); String xml = xs.toXML(array); System.out.println(xml); }}
输出结果:
修改类的全路径为类名
package com.baidu;import java.util.ArrayList;import com.thoughtworks.xstream.XStream;public class Demo { public static void main(String[] args) { User u=new User(); u.setId(11); u.setName("风清扬"); User u1=new User(); u1.setId(12); u1.setName("小师妹"); ArrayListarray=new ArrayList (); array.add(u); array.add(u1); //将集合转换为xml XStream xs=new XStream(); xs.useAttributeFor(User.class, "id"); xs.useAttributeFor(User.class,"name"); xs.alias("User", User.class); String xml = xs.toXML(array); System.out.println(xml); }}
输出结果:
使用jquery来解析xml(dom)
` $.post("${pageContext.request.contextPath}/GetCityServlet", {"pid":pv},function(data) { $("#city").html(""); $(data).find("Cities").each(function(){ /**/ //alert($(this).html()); $("#city").append(""); }); }); 18 140300 阳泉市 140000
$.post("${pageContext.request.contextPath}/GetCityServlet", {"pid":pv},function(data) { $("#city").html(""); $(data).find("Cities").each(function(){ /**/ //alert($(this).attr("city")); $("#city").append(""); }); }); }); 15 130000