8

I'm converting GPathResult to String using

def gPathResult = new XmlSlurper().parseText('<node/>')
XmlUtil.serialize(gPathResult)

It works fine, but I'm getting XML declaration in front of my XML

<?xml version="1.0" encoding="UTF-8"?><node/>

How can I convert GPathResult to String without <?xml version="1.0" encoding="UTF-8"?> at the beginning?

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103

4 Answers4

9

Use XmlParser instead of XmlSlurper:

def root = new XmlParser().parseText('<node/>')
new XmlNodePrinter().print(root)

Using new XmlNodePrinter(preserveWhitespace: true) may be your friend for what you're trying to do also. See the rest of the options in the docs: http://docs.groovy-lang.org/latest/html/gapi/groovy/util/XmlNodePrinter.html.

thecodesmith_
  • 1,277
  • 8
  • 18
1

This is the code in the XmlUtil class. You'll notice it prepends the xml declaration so it's easy enough to just copy this and remove it:

private static String asString(GPathResult node) {
    try {
        Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").newInstance();
        InvokerHelper.setProperty(builder, "encoding", "UTF-8");
        Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node);
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString();
    } catch (Exception e) {
        return "Couldn't convert node to string because: " + e.getMessage();
    }

}
Phil Barr
  • 161
  • 1
  • 7
1

You can still use the XmlSlurper than use the serialize it and replace first replaceFirst

 def oSalesOrderCollection = new XmlSlurper(false,false).parse(xas)     
            def xml = XmlUtil.serialize(oSalesOrderSOAPMarkup).replaceFirst("<\\?xml version=\"1.0\".*\\?>", "");
           //Test the output or just print it 
           File outFile = new File("aes.txt")
           Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF8"));
                    out.append(xml.toString())
                    out.flush()
                    out.close()

GroovyCore Snip :

  /**
   * Transforms the element to its text equivalent.
   * (The resulting string does not contain a xml declaration. Use {@code XmlUtil.serialize(element)} if you need the declaration.)
   *
   * @param element the element to serialize
   * @return the string representation of the element
   * @since 2.1
   */
  public static String serialize(Element element) {
    return XmlUtil.serialize(element).replaceFirst("<\\?xml version=\"1.0\".*\\?>", "");
  }
}
napi15
  • 2,354
  • 2
  • 31
  • 55
0

You can use XmlNodePrinter and pass a custom writer, so instead of it print to output it will print to a string:

public static String convert(Node xml) {
    StringWriter stringWriter = new StringWriter()
    XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(stringWriter))
    nodePrinter.print(xml)
    return stringWriter.toString()
}
Topera
  • 12,223
  • 15
  • 67
  • 104