Search code examples
javaxmlxstream

How can I disable unnecessary escaping in XStream?


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

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


Solution

  • 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("]]>"); 
            }
        }
    }