问题
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?
回答1:
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.
回答2:
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();
}
}
回答3:
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()
}
来源:https://stackoverflow.com/questions/38917892/gpathresult-to-string-without-xml-declaration