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?
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.
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();
}
}
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\".*\\?>", "");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With