I’m using Groovy and I’m trying to insert an xml node into a xml document parsed with XmlSlurper.
I manage to add the node at the end of the document but not where I really need to.
Original doc:
<xml-fragment xmlns:ser="http://www.bea.com/wli/sb/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:con="http://www.bea.com/wli/sb/pipeline/config">
<ser:coreEntry isProxy="true" isEnabled="true" isTracingEnabled="false">
<ser:binding type="SOAP" isSoap12="false" xsi:type="con:SoapBindingType" xmlns:con="http://www.bea.com/wli/sb/services/bindings/config">
<con:wsdl ref="bus/src/main/osb/interfaces/apilink/ChargeServices"/>
<con:port>
<con:name>ChargeServicesPort</con:name>
<con:namespace>java:dk.tdc.apilink.logic.sessions.interfaces</con:namespace>
</con:port>
<con:selector type="SOAP body"/>
</ser:binding>
</ser:coreEntry>
</xml-fragment>
Fragment to add
def fragmentToAddXml = '''
<ser:security xmlns:ser="http://www.bea.com/wli/sb/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:con="http://www.bea.com/wli/sb/pipeline/config">hello</ser:security>
'''
This is the code I’m using.
def root = new XmlSlurper().parseText(file.getText())
root.'core-entry'.appendNode( fragmentToAddXml )
def xmlBuilder = new groovy.xml.StreamingMarkupBuilder().bind{ mkp.yield root }
Please note that the new node should be placed before the “ser:binding” node.
The result should be:
<xml-fragment xmlns:ser="http://www.bea.com/wli/sb/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:con="http://www.bea.com/wli/sb/pipeline/config">
<ser:coreEntry isProxy="true" isEnabled="true" isTracingEnabled="false">
<ser:security xmlns:ser="http://www.bea.com/wli/sb/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:con="http://www.bea.com/wli/sb/pipeline/config">hello</ser:security>
<ser:binding type="SOAP" isSoap12="false" xsi:type="con:SoapBindingType" xmlns:con="http://www.bea.com/wli/sb/services/bindings/config">
<con:wsdl ref="bus/src/main/osb/interfaces/apilink/ChargeServices"/>
<con:port>
<con:name>ChargeServicesPort</con:name>
<con:namespace>java:dk.tdc.apilink.logic.sessions.interfaces</con:namespace>
</con:port>
<con:selector type="SOAP body"/>
</ser:binding>
</ser:coreEntry>
</xml-fragment>
Thanks
Luciano
Given the xml (in a string for testing)
And the xml you want to add as:
Then you can parse them both (with
XmlSlurperset to use namespaces via the 2ndtrueparameter)Append the xml to add to the
datanode (as you want it insidedata, notlastname)Then print it out:
Which prints:
Which I believe is correct (not formatted 100% as I’d like, but correct) 😉
Edit
If order is important, you can use
XmlParserlike so: