7

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

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

skaffman
  • 390,936
  • 96
  • 800
  • 764
mike g
  • 1,781
  • 1
  • 18
  • 25

3 Answers3

7

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
  • 72,880
  • 29
  • 134
  • 165
  • 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 May 24 '10 at 16:24
  • Note that this behaviour switches off escaping globally for your XStream object. If you only want to disable escaping when the text contains ' – John Rix Mar 19 '15 at 13:52
  • The code that constructs the CDATA section should also contain an exclamation mark, as in `writer.write(" – Simon White Aug 08 '18 at 14:14
1

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[]{"<","\"","'",">"});
Kumar Abhishek
  • 2,734
  • 30
  • 28
0

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
  • 18,172
  • 4
  • 63
  • 94