%dw 2.0
output application/xml
---
{
Result: {
(payload.Names.*NameDetail map ( nameDetail , indexOfNameDetail ) -> {
TargetName @((nameDetail.@)): {
item: nameDetail.item
}
})
}
}
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 2.x versions of DataWeave are used by Mule 4 apps. For
DataWeave in Mule 3 apps, refer to
DataWeave version 1.2 examples.
For other DataWeave versions, you can use the version selector in the DataWeave 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.
<?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>
<?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>