动态添加新的 XML 节点,带有 N 个嵌套标签。

huangapple go评论56阅读模式
英文:

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&#39;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>



huangapple
  • 本文由 发表于 2023年2月18日 23:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定