mule-user
mule-user

Reputation: 223

For loop and when condition in mule dataweaver

I have an input xml file as below where I have multiple segments for LineError

 <LineErrors>
    <LineError>
      <LineErrorType>CARGO REPORT SAC</LineErrorType>
      <LineErrorID>CARGO REPORT SAC</LineErrorID>
      <LineErrorDescription>N/A</LineErrorDescription>
    </LineError>
    <LineError>
      <LineErrorType>CONSOLIDATED STATUS</LineErrorType>
      <LineErrorID>CONSOLIDATED STATUS</LineErrorID>
      <LineErrorDescription>HELD</LineErrorDescription>
    </LineError>
</LineErrors>

Now in dataweaver I am producing another xml file where an attribute is mapped to fixed value if there are any LineError segment Containing LineErrorDescription field as value "Held". For example id = "x" if LineErrors.LineError.LineErrorDescription == "Held"

So my question is how in dataweaver we can iterate and compare. Please share if you have any clue.

Upvotes: 0

Views: 9112

Answers (2)

Manik Magar
Manik Magar

Reputation: 1401

You can use filter and map together, try this -

%dw 1.0
%output application/xml
---
payload.LineErrors.*LineError filter ($.LineErrorDescription == 'HELD') map {
   id: 'X'
}

Upvotes: 3

danw
danw

Reputation: 1648

Have you looked at the documentation for DataWeave? I'd recommend that as a starting point. An example from the documentation which should get you going is as follows:

With the following input:

<users>
  <user>
    <name>Mariano Achaval</name>
    <phone>152235465654</phone>
    <street>Laprida 924</street>
  </user>
  <user>
    <name>Martin Alejandro Cousido</name>
    <phone>15332255555</phone>
    <street>Acassuso 2280</street>
  </user>
</users>

Using the following DW script - take note of the way secondName is generated:

%dw 1.0
%output application/json
%function words(name) name splitBy " "
---
contacts: payload.users.*user map using (parts =  words($.name)){
  firstName: parts[0],
  (secondName: parts[1]) when (sizeOf parts) > 2,
  lastName: parts[-1],
  email:((lower $.name) replace " " with ".") ++ "@acme.com",
  address: $.street
}

Yields the following output:

{
  "contacts": [
    {
      "firstName": "Mariano",
      "lastName": "Achaval",
      "email": "[email protected]",
      "address": "Laprida 924"
    },
    {
      "firstName": "Martin",
      "secondName": "Alejandro",
      "lastName": "Cousido",
      "email": "[email protected]",
      "address": "Acassuso 2280"
    }
  ]
}

I'd suggest off the back of the above example you attempt to achieve what you have explained in your original question and should you run in to any issues, raise a new question with an example of the DW script you are working with to reach out for further advice. That way you will be able to target more specific issues rather than have SO do the work for you.

Hope this helps.

Upvotes: 1

Related Questions