5

Here is my xml, in that first I need to check 'RecordsEntries' should not be 'null', then RecordEntry shouldn't be null followed by mapping code

<?xml version="1.0" encoding="UTF-8"?>
<Records>
  <storenumber />
  <calculated>false</calculated>
  <subTotal>12</subTotal>
 <RecordsEntries>
   <RecordEntry>
     <deliverycharge>30.0</deliverycharge>
     <entryNumber>8</entryNumber>
     <Value>true</Value>
  </RecordEntry>
  <RecordEntry>
    <deliverycharge>20.0</deliverycharge>
    <entryNumber>7</entryNumber>
    <Value>false</Value>
  </RecordEntry>
</RecordsEntries>
 <RecordsEntries>
    <RecordEntry>
      <deliverycharge>30.0</deliverycharge>
      <entryNumber>8</entryNumber>
      <Value>false</Value>
    </RecordEntry>
 </RecordsEntries>
</Records>

Tried multiple scenario's also used when condition checking but somewhere missing parenthesis or correct format

    orders: {
    order: {
  StoreID: payload.Records.storenumber,
  Total: payload.Records.calculated,
 (( payload.Records.RecordsEntries.*RecordEntry ) map {
    IndividualEntry: {
    Number:$.entryNumber,
    DeliverCharge:$.deliverycharge
    }
  } when ( payload.Records.RecordsEntries != null and payload.Records.RecordsEntries.*RecordEntry !=null))}
}

getting error like missing ). Tried other way around by checking the null condition directly inside the first loop got error like "Cannot coerce array to an boolean". Please suggest. Thanks.

star
  • 1,493
  • 1
  • 28
  • 61

2 Answers2

6

You can instead do

%dw 1.0
%output application/xml
---
orders: {
  order: {
  StoreID: payload.Records.storenumber,
  Total: payload.calculated,
 ((payload.Records.*RecordsEntries.*RecordEntry default []) map {
      IndividualEntry: {
        Number:$.entryNumber,
        DeliverCharge:$.deliverycharge
      }
    })
  }
}

DataWeave is "null-safe" for querying values like in payload.Records.*RecordsEntries.*RecordEntry, but an error will be thrown when trying to operate with a null (e.g. null map {}).

The default operator replaces the value to its left, if it's null, with the one on the right.

Also you were missing an *. You need to use it in xml whenever you want all the repetitive elements that match.

Shoki
  • 1,508
  • 8
  • 13
0

If you want to skip a particular field assignment in dataweave based on the null or blank , below mentioned script can be used.

payload map ((payload01 , indexOfPayload01) -> { Name: payload01.Name, (LastName: payload01.LastName) when payload01.LastName !=null and payload01.LastName !='' })

This will skip the field mapping for Name , if the name field is coming as null or blank in the incoming payload.

Soumya
  • 59
  • 7
  • you can not use when without otherwise – Satheesh Kumar Jan 05 '17 at 12:11
  • In the above mentioned syntax i m skipping the field assignment for lastname when the value in the input side is null. In this case when can be used without otherwise. I have used this many times. – Soumya Mar 28 '17 at 15:15