How can I disable unnecessary escaping in XStream?

99封情书 提交于 2019-12-09 17:41:29

问题


XStream by default unnecessarily escapes >," ... etc.

Is there a way to disable this (and only escape <, &)?


回答1:


This is the result of the default PrettyPrintWriter. Personally, I like to escape both < and >. It makes the output look more balanced.

If you want canonicalized XML output, you should use the C14N API provided in Java.

If the streamed content includes XML, CDATA is a better option. Here is how I did it,

XStream xstream = new XStream(
           new DomDriver() {
               public HierarchicalStreamWriter createWriter(Writer out) {
                   return new MyWriter(out);}});
String xml = xstream.toXML(myObj);

    ......

public class MyWriter extends PrettyPrintWriter {
    public MyWriter(Writer writer) {
        super(writer);
    }

    protected void writeText(QuickWriter writer, String text) { 
        if (text.indexOf('<') < 0) {
            writer.write(text);
        }
        else { 
            writer.write("<[CDATA["); writer.write(text); writer.write("]]>"); 
        }
    }
}



回答2:


Cdata does not worked for me, Finally i have to work with Apache StringUtils.

StringUtils.replaceEach(xml, new String[]{"&lt;","&quot;","&apos;","&gt;"}, new String[]{"<","\"","'",">"});



回答3:


XStream doesn't write XML on its own, it uses various libs ("drivers"?) to do so.

Just choose one which doesn't. The list is on their site. I guess it would use XOM by default.



来源:https://stackoverflow.com/questions/2891305/how-can-i-disable-unnecessary-escaping-in-xstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!