標籤:xml xstream
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對象轉換為XMLxstream.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; }}
是不是覺得很簡單呢
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
xstream的簡單使用