Home > Back-end >  Dataweave 2.0 - How to obtain an XML elements value, based on it's attribute name
Dataweave 2.0 - How to obtain an XML elements value, based on it's attribute name

Time:10-16

I'm trying to work out how to extract an XML element value from a repeating list of elements with the same name, but different attribute names.

In this case, how would you extract the element value ('ABC') for the element with attribute name 'xxx.UDFCHAR10', in DataWeave 2.0?

<root>
   <UserArea>
      <PropertyList>
         <Property>
            <NameValue name="xxx.CreatedBy">Test 1</NameValue>
         </Property>
         <Property>
            <NameValue name="xxx.EnteredBy">Test 2</NameValue>
         </Property>
         <Property>
            <NameValue name="xxx.SafetyFlag">false</NameValue>
         </Property>
         <Property>
            <NameValue name="xxx.DependFlag">true</NameValue>
         </Property>
         <Property>
            <NameValue name="xxx.UDFCHAR10">ABC</NameValue>
         </Property>
      </PropertyList>
   </UserArea>
</root>

Thanks

CodePudding user response:

Use the multi-valued selector to get all the repeated instances into an array, then you can filter by the value of the attribute using the attribute selector on the element that has it. This method will return an array of the extracted values, however if you know there is going to be only one element you can extract it by index [0].

Note that your description is not really accurate because the attribute is in a sub element of the repeating element.

%dw 2.0
output application/java
---
(payload.root.UserArea.PropertyList.*Property 
    filter ($.NameValue.@name == "xxx.UDFCHAR10")).NameValue

Output:

[
  "ABC"
]
  • Related