How to print the escape characters as it is while using PrettyPrintWriter?

144 views Asked by At

Using PrettyPrintWriter to pretty print the xml file In the generated xml file the ' (apostrophe) is getting written as &apos Want it to print as '

Using the following xstream.marshal(obj, new PrettyPrintWriter(writer)) to pretty print ,any suggestions on how to print the escape characters as it is?

1

There are 1 answers

0
andrewJames On

You can provide your own implementation of PrettyPrintWriter, which extends that class and overrides its writeText(QuickWriter, String) method.

In its most basic form that would be something like this:

import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import java.io.Writer;

public class MyPrettyPrintWriter extends PrettyPrintWriter {

    public MyPrettyPrintWriter(Writer writer) {
        super(writer);
    }

    @Override
    public void writeText(QuickWriter writer, String string) {
        writer.write(string); 
    }
}

You would use this as follows:

String s = "Foo'Bar";
XStream xstream = new XStream();
FileWriter writer = new FileWriter("my_demo.xml");
xstream.marshal(s, new MyPrettyPrintWriter(writer));

The output file contains the following:

<string>Foo'Bar</string>

This is basic - it just passes the tag contents through to the file unchanged - nothing is escaped.

You are OK for content containing ", ' and >. But this will be a problem for text containing > and & - which should still be escaped. So you can enhance your writeText method to handle those cases as needed. See What characters do I need to escape in XML documents? for more details.

Note also this is only for text values - not for XML attributes. There is a separate writeAttributeValue method for that (probably not needed in your scenario).


It is worth adding: There should be no need to do any of this. The XML is valid, with escaped values such as &apos;. Any process (any half-way decent XML library or tool) reading that data should handle them correctly.