经过多次调试,终于得到了有效的结果,方法如下:
public class XStreamFactory { public static XStream getXStream() { final NameCoder nameCoder = new NoNameCoder(); XStream xStream = new XStream(new XppDomDriver(nameCoder) { @Override public HierarchicalStreamWriter createWriter(Writer out) { //输出格式化的xml字符串 //return new PrettyPrintWriter(out, nameCoder) { //输出压缩的xml字符串,删除多余的空白符 return new CompactWriter(out, nameCoder) { boolean cdata = false; @Override public void startNode(String name, Class clazz) { super.startNode(name, clazz); // 所有的字符串都加上CDATA标识 cdata = "String".equals(clazz.getSimpleName()); } @Override protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); return xStream; } }
使用方法如下:
XStream xStream = XStreamFactory.getStream(); // xml to java object xStream.ignoreUnknownElements(); xStream.alias("xml", Class<待转换的java object>); xStream.fromXML("<xml><tag>aaa</tag></xml>"); // java object to xml xStream.toXML(java object);
时间: 2024-10-13 10:23:36