xstream也是一个比较好用的java对象转xml的工具,之前由于长期使用dom4j的缘故,都没研究过这玩意儿,最近由于搞微信开发的缘故要生成xml,但是又觉得dom4j有点繁琐,之后就找到了xstream的资料,顺便学了下觉得还是挺好用,因此推荐给大家。
1 jar包的下载地址
http://xstream.codehaus.org/download.html
这里推荐使用1.3.1这个版本,貌似大部分人都用的这个
2 xstream的基本使用
(1) xstream的初始化
(2)设置别名
(3)转换
// XStream初始化 XStream xstream = new XStream(); XStream xstream = new XStream(new DomDriver()); // 设置别名(可选) xstream.alias("person", Person.class); // 将Java对象转换为XML xstream.toXML(person); // 将XML转换为Java对象 Person person = xstream.fromXML(xml);
这段代码大部分还是实用,但是如果有特殊字符如 > , < , &就会出现解析错误 ,因此要给xml添加扩展,反正就是一大堆的内部类,来一起看下
//xstream扩展 private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // 对所有xml节点都增加CDATA标记 boolean cdata = true; public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } });
看着有点恐怖啊,不过又没必要背下来
3 赖看下我写的一个工具类
package org.lxh; import java.io.Writer; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; public class XstreamUtil { //xstream扩展 private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // 对所有xml节点都增加CDATA标记 boolean cdata = true; public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); public String object2Xml(Object obj,Object child,String alias,String aliasForChild){ xstream.alias(alias, obj.getClass()); xstream.alias(aliasForChild, child.getClass()); String xml=xstream.toXML(obj); return xml; } public String object2Xml(Object obj,String alias){ xstream.alias(alias, obj.getClass()); String xml=xstream.toXML(obj); return xml; } }
是不是觉得很简单呢
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-25 07:22:52