Reputation: 11
I am using dataweave
for transforming XML to CSV. I want to know how to implement nested for loop in dataweave
.
Below is the input xml:
<employee>
<id>1236</id>
<emplinfo>
<emplid>1961</emplid>
<jobinfo>
<status>T</status>
<title>Manager</title>
<start_date>2016-09-01</start_date>
</jobinfo>
<jobinfo>
<status>P</status>
<end_date>2016-08-31</end_date>
<title>Integration Manager</title>
<start_date>2016-08-01</start_date>
</jobinfo>
<jobinfo>
<status>A</status>
<end_date>2016-07-31</end_date>
<title>Communications Manager</title>
<start_date>2016-07-17</start_date>
</jobinfo>
</emplinfo>
<emplinfo>
<emplid>1801</emplid>
<jobinfo>
<status>T</status>
<title>AM</title>
<start_date>2016-09-01</start_date>
</jobinfo>
</emplinfo>
</employee>
Excepted output:
id empl_id status end_date title start_date
1236 1961 T Manager 2016-09-01
1236 1961 P 2016-08-31 Integration Manager 2016-08-01
1236 1961 A 2016-07-31 Communications Manager 2016-07-17
1236 1801 T AM 2016-09-01
Any help is greatly appreciated.
Upvotes: 0
Views: 7260
Reputation: 92
You have to use map operator for looping through the members of an array. The left hand side of map is the array which is processed and right hand side will have code for how members in it should be mapped. We can use lambda functions as well. You can name the current member and refer it as well.
(payload.ARRAY map ((value,index) ->
{
id: parent.id,
emplid : value.emplid,
status: value.status,
}
)
Similiar depending on how you want to process the input array we can have nested map operators.
(payload.ARRAY map ((value,index) ->
{
(payload.ARRAY2 map ((value,index) ->
{
id: parent.id,
emplid : value.emplid,
status: value.status,
}
)
Upvotes: 0
Reputation: 69
Do it something like this
Segment:(payload.segments map ((segment, segmentIndex)->
{
Leg:(segment.legs map ((leg, legIndex)->
{
Origin:leg.departureField.airportCodeField,
Destination:leg.arrivalField.airportCodeField
}))
}))
Upvotes: 0
Reputation: 2415
This works for me.
%dw 1.0
%output application/csv
---
flatten (payload map ((parent, parentindex) -> {
emplinfo:(parent.*emplinfo map ((emplinfo,empindex) -> {
jobinfo:(emplinfo.*jobinfo map ((jobinfo,jobindex) -> {
id: parent.id,
emplid : emplinfo.emplid,
status: jobinfo.status,
end_date:jobinfo.end_date,
title:jobinfo.title,
start_date:jobinfo.start_date
}))
}))
}))..jobinfo
I have used normal csv. you can choose any kind of format. Output is
id,emplid,status,end_date,title,start_date
1236,1961,T,,Manager,2016-09-01
1236,1961,P,2016-08-31,Integration Manager,2016-08-01
1236,1961,A,2016-07-31,Communications Manager,2016-07-17
1236,1801,T,,AM,2016-09-01
Hope this helps.
Upvotes: 2