7

我正在转换GPathResultString使用

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

它工作正常,但我在我的 XML 前面得到了 XML 声明

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

我如何在一开始就转换GPathResultString没有<?xml version="1.0" encoding="UTF-8"?>

4

4 回答 4

9

使用XmlParser代替XmlSlurper

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

使用new XmlNodePrinter(preserveWhitespace: true)可能也是您尝试做的事情的朋友。请参阅文档中的其余选项:http ://docs.groovy-lang.org/latest/html/gapi/groovy/util/XmlNodePrinter.html 。

于 2016-08-14T04:09:49.580 回答
1

这是 XmlUtil 类中的代码。您会注意到它预先添加了 xml 声明,因此很容易复制并删除它:

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();
    }

}
于 2017-04-19T15:30:02.017 回答
0

您可以使用XmlNodePrinter并传递自定义编写器,因此它不是打印到输出,而是打印到一个字符串:

public static String convert(Node xml) {
    StringWriter stringWriter = new StringWriter()
    XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(stringWriter))
    nodePrinter.print(xml)
    return stringWriter.toString()
}
于 2020-01-21T18:03:11.150 回答
0

您仍然可以使用XmlSlurper而不是使用序列化它并首先替换 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 截图

  /**
   * 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\".*\\?>", "");
  }
}
于 2021-11-09T03:28:34.180 回答