Contact Us 1-800-596-4880

Pass XML Attributes

DataWeave enables you to pass attributes from within an XML tag input source to the target output XML. The DataWeave example shows how to pass the XML attributes in the NameDetail field of the input source payload to the TargetName field of the XML output. Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave version 1 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

This example uses: - .* multivalue selector that returns an array of NameDetail elements. - map function to iterate over the array of NameDetail elements of the input. - The dynamic attribute expression @dynamicAttributes to create the attributes of the new output tag by selecting the attributes dynamically from the input.

DataWeave Script:
%dw 2.0
output application/xml
---
{
    Result: {
        (payload.Names.*NameDetail  map ( nameDetail , indexOfNameDetail ) -> {
            TargetName @((nameDetail.@)): {
                item: nameDetail.item
            }
        })
    }
}
Input XML Payload:
<?xml version="1.0" encoding="UTF-8"?>
      <Names>
         <NameDetail NameId="11111" NameType="Person" Name="Richarson" GivenNames="John" PreferredLanguage="English" CompanyNumber="" Gender="Male" Title="" >
            <item>doo</item>
         </NameDetail>
         <NameDetail NameId="22222" NameType="Person" Name="Richarson" GivenNames="Susan" PreferredLanguage="Spanish" CompanyNumber="" Gender="Female" Title="" >
            <item>dah</item>
         </NameDetail>
         <NameDetail NameId="33333" NameType="Person" Name="Knox" GivenNames="Frances" PreferredLanguage="English" CompanyNumber="" Gender="Male" Title="" >
            <item>dab</item>
         </NameDetail>
      </Names>
Output XML:
<?xml version='1.0' encoding='UTF-8'?>
<Result>
  <TargetName NameId="11111" NameType="Person" Name="Richarson" GivenNames="John" PreferredLanguage="English" CompanyNumber="" Gender="Male" Title="">
    <item>doo</item>
  </TargetName>
  <TargetName NameId="22222" NameType="Person" Name="Richarson" GivenNames="Susan" PreferredLanguage="Spanish" CompanyNumber="" Gender="Female" Title="">
    <item>dah</item>
  </TargetName>
  <TargetName NameId="33333" NameType="Person" Name="Knox" GivenNames="Frances" PreferredLanguage="English" CompanyNumber="" Gender="Male" Title="">
    <item>dab</item>
  </TargetName>
</Result>