GPathResult for String without XML declaration

I convert GPathResultto Stringusing

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

It works fine, but I get an XML declaration in front of my XML

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

How to convert GPathResultto Stringwithout <?xml version="1.0" encoding="UTF-8"?>at the beginning?

+5
source share
3 answers

Use XmlParserinstead XmlSlurper:

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

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

+8
source

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

}
+1

, ""

Got the previous answer on using xmlparser. But we have a restriction on the use of xmlslurper, how can we fix it (or remove it) using xmlslurper?

Our great code snippet

def xmlFromFile = new File(xxx.xml)
def envelopeNode = new XmlSlurper( false, false ).parseText(xmlFromFile.getText())
def newNode = new XmlSlurper().parseText(SomeStringWithProperXMLChildNode)
envelopeNode.rows.appendNode(newNode)
XmlUtil xmlUtil = new XmlUtil()
xmlUtil.serialize(envelopeNode, new FileWriter(xmlFromFile))

XML snippet:

<SomeThing xmlns="http://xmlns.oracle.com/something" name="something">
   <description />
   <columns>
      <column name="name" />
      <column name="Type" />
      <column name="Identifier" />
   </columns>
   <rows>
      <row>
         <cell>111</cell>
         <cell>222</cell>
         <cell>333</cell>
      </row>
      <row>
         <cell>444</cell>
         <cell>555</cell>
         <cell>666</cell>
      </row>
   </rows>
</SomeThing>

How can I remove the "" or can stop serialize / XmlSlurper from adding this extra encoding information.

thank

+1
source

Source: https://habr.com/ru/post/1651067/


All Articles