Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GPathResult to String without XML declaration

Tags:

xml

groovy

gpath

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?

like image 902
Michal Kordas Avatar asked Aug 12 '16 12:08

Michal Kordas


3 Answers

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.

like image 194
thecodesmith_ Avatar answered Oct 20 '22 03:10

thecodesmith_


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

}
like image 1
Phil Barr Avatar answered Oct 20 '22 01:10

Phil Barr


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\".*\\?>", "");
  }
}
like image 1
napi15 Avatar answered Oct 20 '22 01:10

napi15