如何从XML中提取所有嵌套的子节点?

时间:2019-05-11 05:11:28

标签: anypoint-studio dataweave mule4

我有一个带有这样的嵌套grandChild节点的简单XML

<parent>
    <child type="reference">
        <grandChild name="aaa" action="None">
            <Attribute name="xxx">1</Attribute>
            <grandChild name="bbb" action="None">
                <Attribute name="xxx">1</Attribute>
            </grandChild>
            <grandChild name="ccc" action="None">
                <Attribute name="xxx">1</Attribute>
            </grandChild>
        </grandChild>
        <grandChild name="ddd" action="None">
                <Attribute name="xxx">1</Attribute>
        </grandChild>
    </child>
</parent>

我只想提取所有grandChild节点的列表。我可以在迭代每个节点的同时实现,这为我提供了一个级别的列表,但没有列出整个XML。单一数据编织是否可以实现?

我简单的数据编织看起来像这样

%dw 2.0
output application/json
---
payload.parent.child.*grandChild.*grandChild map {
    "@name": $.@name,
    "Attribute" : $.*Attribute map {
        "@name" : $.@name,
        "#text" : trim($)
    }
}

所需的输出

[
  {
    "@name": "bbb",
    "Attribute": [
      {
        "@name": "xxx",
        "#text": "1"
      }
    ]
  },
  {
    "@name": "ccc",
    "Attribute": [
      {
        "@name": "xxx",
        "#text": "1"
      }
    ]
  },
  {
    "@name": "aaa",
    "Attribute": [
      {
        "@name": "xxx",
        "#text": "1"
      }
    ]
  },
  {
    "@name": "ddd",
    "Attribute": [
      {
        "@name": "xxx",
        "#text": "1"
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:0)

这似乎可行:

payload..*grandChild map ( ( elt, index) ->
    {
        "@name": elt.@name,
        "Attribute": elt.*Attribute map ( (attrElt, attrIndex) ->
        {  "@name": attrElt.@name,
            "#text": trim(attrElt)
        }
        )
    }
)