tags:

views:

170

answers:

2

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

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

A: 

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.

alamar
+2  A: 

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("]]>"); 
        }
    }
}
ZZ Coder
A CDATA section is not an complete alternative to escaping, as the sequence `]]>` can't go in it. (It's sometimes escaped into two CDATA sections.)
bobince