首页 > 解决方案 > 如何从 XML 中提取所有嵌套的子节点?

问题描述

我有一个像这样嵌套的 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"
      }
    ]
  }
]

标签: anypoint-studiodataweavemule4

解决方案


这似乎有效:

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

推荐阅读