Home > OS >  Gradle Groovy XmlUtil serialize escapes special characters in attribute values
Gradle Groovy XmlUtil serialize escapes special characters in attribute values

Time:10-27

I have created a task in my build.gradle which modifies an XML file. However, when I use XmlUtil.serialize and write the modified structure back to the file, special characters inside attributes are escaped.

For example:

    <foo name="a.b.>">
    </foo>

becomes:

    <foo name="a.b.&gt;">
    </foo>

How can I prevent this from happening? I've already tried XmlNodePrinter, but this has the same result. I also tried using jdom2 (adding a buildscript dependency), but the build script could not find jdom2. So I haven't been able to try and see whether this works.

CodePudding user response:

As it turns out, XmlUtil internally uses XmlNodePrinter. And inside XmlNodePrinter it is hard-coded that attribute values are always escaped. I solved this by creating a custom implementation of XmlNodePrinter which doesn't escape the values.

class CustomXmlNodePrinter extends XmlNodePrinter {
    CustomXmlNodePrinter(final PrintWriter out) {
        super(out);
    }

    @Override
    protected void printNameAttributes(final Map attributes, final XmlNodePrinter.NamespaceContext ctx) {
        if (attributes == null || attributes.isEmpty()) {
            return;
        }
        for (final Object p : attributes.entrySet()) {
            final Map.Entry entry = (Map.Entry) p;
            out.print(" ");
            out.print(entry.getKey());
            out.print("=");
            out.print(quote);
            out.print(entry.getValue());
            out.print(quote);
            printNamespace(entry.getKey(), ctx);
        }
    }
}
  • Related