Xstream介绍
Xstream是一种OXMapping 技术,是用来处理XML文件序列化的框架,在将JavaBean序列化,或将XML文件反序列化的时候,不需要其它辅助类和映射文件,使得XML序列化不再繁索。Xstream也可以将JavaBean序列化成Json或反序列化,使用非常方便。
序列化javaBean的list集合
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 模拟一个product集合
Product product1 = new Product("宝马", 6.66);
Product product2 = new Product("奔驰", 18.9);
List<Product> list = new ArrayList<Product>();
list.add(product1);
list.add(product2);
// 创建序列化对象
XStream xstream = new XStream();
String xml = xstream.toXML(list);
//给序列化后的xml文件,节点起别名
xstream.alias("product", Product.class);
xstream.alias("proudctS", List.class);
System.out.println(xml);
}
<list>
<cn.wang.domain.Product>
<name>宝马</name>
<price>6.66</price>
</cn.wang.domain.Product>
<cn.wang.domain.Product>
<name>奔驰</name>
<price>18.9</price>
</cn.wang.domain.Product>
</list>
设置了别名之后
<proudctS>
<product>
<name>宝马</name>
<price>6.66</price>
</product>
<product>
<name>奔驰</name>
<price>18.9</price>
</product>
</proudctS>
jquery解析xml文件
<script type="text/javascript">
$(function(){
$("#showProduct").click(function(){
//alert("aa");
$.get("${pageContext.request.contextPath}/demo3Servlet",function(data){
//回调函数中的参数就是返回的值
//alert(data);
//console.info(data);
//解析xml文件
$(data).find("product").each(function(){
var name = $(this).children("name").text();//test和html的区别
//alert(name);
var price = $(this).children("price").text();
});
});
});
});
</script>