7

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

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
mike g
  • 1,791
  • 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
  • 74,484
  • 29
  • 137
  • 169
  • 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 '<' or other specific characters, you can replace `writer.write(text);` with `super.write(writer, text);`, thereby restoring the default escaping behaviour for all other cases. – 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("<![CDATA[");` – 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
  • 3,004
  • 33
  • 29
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,729
  • 4
  • 64
  • 97