Reputation: 166
I have the below sample xml.
<A>
<B>[email protected]</B>
</A>
And I want to insert a new set of xml message tags dynamically using groovy as the below 2 samples. For example every message will have the A,B & C tags. But the nested tags in C tag will be generated dynamically( both name and value of the tag).
Sample 1
<A>
<B>[email protected]</B>
<C>
<Info name="Name">Jane</Info>
<Info name="Age">1</Info>
</C
<C>
<Info name="Name">Kate</Info>
<Info name="Age">100</Info>
</C>
</A>
Sample 2
<A>
<B>[email protected]</B>
<C>
<Info name="Name">Hello</Info>
<Info name="Age">100</Info>
<Info name="Country">Test</Country>
</C
<C>
<Info name="Name">Hello world</Info>
<Info name="Age">200</Info>
<Info name="Country">USA</Country>
</C
</A>
I tried to achieve it by using appendNode to construct the tags dynamically and insert it under C tag. But couldn't find a way to map the nested tags under C tag dynamically. Because at times it can be 1 parameter or 100 parameters under the C tag with name and values.
def root = new XmlSlurper(false, false).parseText(xmlAsString)
root.appendNode {
C{
//How to dynamically insert the Parameters if we get to know the parameter list(name and value) at runtime
Info(Name: 'Name','Hello')
Info(Name:'Age','100')
Info(Name:'Country','Test')
}
}
XmlUtil.serialize(root)
Upvotes: 0
Views: 64
Reputation: 38852
I think if I understand what you mean it'd be something like this:
List<Parameter> parameters = [...]
def root = new XmlSlurper(false, false).parseText(xmlAsString)
root.appendNode {
C {
parameters.each { param ->
Info( name: param.name, param.value )
}
}
}
XmlUtil.serialize(root)
Upvotes: 1