0

I'm using XStream 1.4.9 to create XML from POJO classes. By default XStream escapes special characters like '>', '<' etc. Additionally it doubles underscore characters in element and attribute names. I need to disable this behaviour. I was able to get rid of double underscores basing on this solution:

XStream and underscores

Disabling character escaping works with this solution:

How can I disable unnecessary escaping in XStream?

But I'm struggling with combining these approaches to achieve both goals in the same time.

I created custom Writer class ommiting character escaping:

public class NoEscapeWriter extends PrettyPrintWriter {

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

    @Override
    protected void writeText(QuickWriter writer, String text) {
        writer.write(text);
    }
}

I implemented class extending DomDriver overriding createWriter() method and injecting XmlFriendlyNameCoder to its super class:

public class CustomDriver extends DomDriver {

        public CustomDriver() {
            super("UTF-8", new XmlFriendlyNameCoder("_-", "_"));
        }

        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new NoEscapeWriter(out);
        }
}

And I'm generating XML with XStream like this:

XStream xStream = new XStream(new CustomDriver());
xStream.processAnnotations(RootElement.class);
final String s = xStream.toXML(root);

Although it ommits character escaping as expected, it still generates output with double underscores like this:

<ROOT>
    <TEST__ID><![CDATA[]]></TEST__ID>
    <MULTIPLE__PART__NAME><![CDATA[]]></MULTIPLE__PART__NAME>
</ROOT>

I tried to extend DomDriver to inject XmlFriendlyNameCoder("-", "") to ommit double underscore problem and overriding createWriter() method to disable character escaping

0 Answers0