I need help in replace XML node using Groovy script. Each <document_owner__c><value>9231799</value></document_owner__c>
should be replaced with <Manager>1234</Manager>
. Given below sample input and required output.
Input:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<row>
<id>728</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
<row>
<id>713</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
<row>
<id>707</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
</root>
Required Output:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<row>
<id>728</id>
<Manager>1234<Manager>
</row>
<row>
<id>713</id>
<Manager>1234<Manager>
</row>
<row>
<id>707</id>
<Manager>1234<Manager>
</row>
</root>
CodePudding user response:
Here is a solution using DataWeave. I wrote a parametrized function that recursively transforms the desired key and replaces it with a new element, which is an Object in DataWeave types.
%dw 2.0
output application/xml
fun replaceElement(originalObject, key, newObject)=
originalObject match {
case is Object -> originalObject mapObject (if($$ as String == key) newObject else ($$): replaceElement($, key, newObject))
else -> $
}
---
replaceElement(payload, "document_owner__c", {Manager: "1234"})
CodePudding user response:
We have a working jenkins job that does something similar. I have extracted some code from it and modified for your scenario. Heres the Groovy script:
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder
def oldXml = """
<root>
<row>
<id>728</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
<row>
<id>713</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
<row>
<id>707</id>
<document_owner__c>
<value>9231799</value>
</document_owner__c>
</row>
</root>
"""
def root = new XmlSlurper().parseText(oldXml)
root.row
.findAll {it.document_owner__c.value.text().equals('9231799') }
.document_owner__c
.replaceNode { Manager("1234") }
def newXml = XmlUtil.serialize(new StreamingMarkupBuilder().bind {mkp.yield root})
println newXml
Output:
<?xml version="1.0" encoding="UTF-8"?><root>
<row>
<id>728</id>
<Manager>1234</Manager>
</row>
<row>
<id>713</id>
<Manager>1234</Manager>
</row>
<row>
<id>707</id>
<Manager>1234</Manager>
</row>
</root>