'Looping using dataweave
my input xml:
<Root>
<Element>
<Record att="a">value</Record>
<Record att="b">value</Record>
.
.
<Record att="g">value</Record>
<Record att="h">value</Record>
.
.
<Record att="p">value</Record>
.
.
<Record att="t">value</Record>
.
.
<Record att="w">value</Record>
.
.
<Record att="z">value</Record>
</Element>
<Element>
<Record att="a">value</Record>
<Record att="b">value</Record>
.
.
<Record att="g">value</Record>
<Record att="h">value</Record>
.
.
<Record att="p">value</Record>
.
.
<Record att="t">value</Record>
.
.
<Record att="w">value</Record>
.
.
<Record att="z">value</Record>
</Element>
.
.
.
.
.
.
</Root>
The dataweave configuration I tried:
%dw 1.0
%input payload application/xml
%output application/csv
---
payload.root.*Element[0].*Record map {
(id:$.@att) when ($.@att) == "g" or ($.@att) == "t",
(type:($.@att) when ($.@att) == "g" or ($.@att) == "t"
}
The o/p i got in my csv:
id,type (headers)
blanklines
.
.
.
g,g
.
.
.
.
t,t
.
.
The requirement is clear. I need only the Records of Element[0]. My o/p CSV should not have any blank lines. Expected output should be:
id,type
g,g
t,t
I couldnot still understand the syntax and concepts of dataweave for looping. Please help me out. Any better solution is accepted.
Solution 1:[1]
If you don't use the subscript it refers to the first element. You can try removing subscript [0]
%dw 1.0
%input payload application/xml
%output application/csv
---
payload.Root.*Element.*Record map {
(id:$.@att) ,
(type:$.@att)
} filter
Solution 2:[2]
How are you accessing a name attribute (@name) as it isn't in your XML? You should access the 'att' attribute right? (@att)
Did you post the correct code and XML ?
OK This should do the job for you.
%dw 1.0
%input payload application/xml
%output application/csv
---
payload.Root.*Element[0].*Record map {
(id:$.@att) ,
(type:$.@att)
} filter ($.id == "g" or $.type == "t")
Solution 3:[3]
script-:1(if you wan to extract only 1st position object values if @att == g or t )
%dw 2.0
input payload application/xml
output application/csv
---
payload.Root.*Element[0].*Record filter( ["t","g"] contains $.@att) map{
"id" : $.@att,
"type" : $.@att
}
output:-
id,type
g,g
t,t
script-:2(if you wan to extract all the objects values if @att == g or t )
%dw 2.0
input payload application/xml
output application/csv
---
payload.Root.*Element.*Record filter( ["t","g"] contains $.@att) map{
"id" : $.@att,
"type" : $.@att
}
output:-
id,type
g,g
t,t
g,g
t,t
Solution 4:[4]
This code below will work fine
Weave Code
%dw 1.0
%output application/csv
---
payload.Root.*Element[0].*Record filter (($.@att == 'g') or ($.@att == 't')) map {
(id : $.@att),
(type : $.@att)
}
Output
id,type
g,g
t,t
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vikas Periyadath |
Solution 2 | |
Solution 3 | Sandeep Sai Kumar |
Solution 4 | Tunaki |