使用 N 个嵌套标签动态添加新的 xml 节点

问题描述 投票:0回答:0

我有下面的示例 xml.

<A>
  <B>[email protected]</B>           
</A>

我想使用 groovy 动态插入一组新的 xml 消息标签作为以下 2 个示例。例如,每条消息都有 A、B 和 C 标签。但是 C 标签中的嵌套标签将动态生成(标签的名称和值)。

样本 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>

样本 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>

我尝试通过使用 appendNode 动态构造标签并将其插入到 C 标签下来实现它。但是找不到动态映射 C 标签下的嵌套标签的方法。因为有时它可以是带有名称和值的 C 标记下的 1 个参数或 100 个参数。

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
                Parameter(Name: 'Name','Hello')
                Parameter(Name:'Age','100')
                Parameter(Name:'Country','Test')
            }
        }
        XmlUtil.serialize(root)
xml groovy xml-parsing xmlslurper xml-builder
© www.soinside.com 2019 - 2024. All rights reserved.