英文:
Add new xml nodes dynamically with N number of nested tags
问题
def 根 = new XmlSlurper(false, false).parseText(xmlAsString)
根.appendNode {
C{
// 在运行时动态插入参数(名称和值)的方法
Info(Name: 'Name', 'Hello')
Info(Name:'Age','100')
Info(Name:'Country','Test')
}
}
XmlUtil.serialize(根)
英文:
I have the below sample xml.
<A>
<B>Test@yopmail.com</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>Test@yopmail.com</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>Test@yopmail.com</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)
答案1
得分: 1
我认为如果我理解你的意思,代码会是这样的:
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)
<details>
<summary>英文:</summary>
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)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论