In Groovy, you can use groovy.xml.XmlUtil.serialize(GPathResult node)
to convert node to XML String.
to convert node to XML String.
But sometimes the XML you end up with contains tag0 namespace all over
the elements. It happens because the doc contains default namespace
with empty prefix, so groovy uses a default prefix which is "tag0".
The XML is still correct but it would be nice to not have to see that
crap. To do so you need to create a new closure with the node and
explicitly declare an empty string namespace. Then use
StreamingMarkupBuilder to convert the newly created closure to String.
The following code is how you would implement that logic.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public String convertToString(GPathResult doc) { | |
def defaultNamespace = doc.lookupNamespace('') | |
if (defaultNamespace) { | |
def docWithNamespace = { | |
mkp.declareNamespace("": defaultNamespace) | |
out << doc | |
} | |
return new StreamingMarkupBuilder().bind(docWithNamespace) | |
} else { | |
return XmlUtil.serialize(doc as GPathResult) | |
} | |
} |