GPathResult to String without XML declaration

烂漫一生 提交于 2021-02-08 13:48:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!