user94538
user94538

Reputation: 177

Mule Dataweave script for retrieving attributes in Xml

My Input Xml looks like below

<?xml version="1.0" encoding="UTF-8"?>
<elements>
<element>
  <id>123</id>
  <items>
     <item>
        <attributes>
        <attribute attribute-id="test1">attr1</attribute>
         <attribute attribute-id="test2">attr2</attribute>                      
        </attributes>
     </item>
  </items>
</element>
</elements>

I tried with below Dataweave script:

%dw 1.0
%output application/xml
---
{
    elements: {  (payload.elements.*element map {
        element: {
            test1 : $.items.item.attributes.attribute when $.items.item.attributes.attribute.@attribute-id == 'test1' otherwise '', 
            test2 : $.items.item.attributes.attribute when $.items.item.attributes.attribute.@attribute-id == 'test2' otherwise '' 
        }
        }
        )
    }

    }

Expected output:

<?xml version='1.0' encoding='windows-1252'?>
<elements>
  <element>
    <test1>attr1</test1>
    <test2>attr2</test2>
  </element>
</elements>

Actual output:

<?xml version='1.0' encoding='windows-1252'?>
<elements>
  <element>
    <test1>attr1</test1>
    <test2></test2>
  </element>
</elements>

What changes are needed in my data weave script to get the expected output?

Upvotes: 0

Views: 3594

Answers (2)

Abhay
Abhay

Reputation: 324

Check the below script

%dw 1.0
%output application/xml
---
{
    elements: {
        (payload.elements.*element map {
            element: {
                ($.items.item.attributes.*attribute map ((element, index) -> {
                    (element.@attribute-id) : element when element.@attribute-id == "test1" or element.@attribute-id == "test2"
                    otherwise ''
                }))
            }
        }
     )
    }
}

It checks the attribute-id for "test1 and test2", if different sets the value as empty.

Upvotes: 0

AnupamBhusari
AnupamBhusari

Reputation: 2415

Try this

%dw 1.0
%output application/xml
---
{
    elements: {  (payload.elements.*element map {
        element: {($.items.item.attributes.*attribute map {
            ($.@attribute-id) : $
        })}
        }
     )
    }

Yours is not working as there are multiple items.item.attributes.attribute

Hope this helps.

Upvotes: 2

Related Questions