码迷,mamicode.com
首页 > 其他好文 > 详细

关于XStream双下划线问题的处理

时间:2015-11-04 17:56:10      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

经过多次调试,终于得到了有效的结果,方法如下:

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);



关于XStream双下划线问题的处理

标签:

原文地址:http://my.oschina.net/02471/blog/525885

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!