Search code examples
muledataweave

dataweave script to iterate over a nested array of string literals


So I have the following payload :

<?xml version="1.0" encoding="utf8" ?>
<Output>
    <Error>
        <Status>0</Status>
        <Details>No errors</Details>
    </Error>
    <Synopsis>
        <Count>451</Count>
    </Synopsis>
    <BankAccounts>
        <BankAccount AcctNo="103" CustName="Frank" BalanceAmount="" Inactive="N" NoOfAccounts="1" >
            <Addresses>
                <Address>ABC</Address>
                <Address>XYZ</Address>
            </Addresses>
        </BankAccount>
        <BankAccount AcctNo="101" CustName="Jane" BalanceAmount="10005" Inactive="N" NoOfAccounts="1" >
            <Addresses>
                <Address>LMN</Address>
                <Address>QWE</Address>
            </Addresses>
        </BankAccount>
        
    </BankAccounts>
</Output>

I need to convert it into the following json :

[
  {
    "accountNumber": "103",
    "customerName": "Frank",
    "balanceAmount": "",
    "inactive": "N",
    "noOfAccounts": "1",
    "address": [
      "ABC","XYZ"
    ]
  },
  {
    "accountNumber": "101",
    "customerName": "Jane",
    "balanceAmount": "10005",
    "inactive": "N",
    "noOfAccounts": "1",
    "address": [
      "LMN","QWE"
    ]
  }
]

I am nearly there using the below dataweave script:

%dw 2.0
output application/json writeAttributes=true
---
 payload.Output.BankAccounts.*BankAccount map {
     accountNumber: $.@AcctNo,
     customerName: $.@CustName,
    balanceAmount: $.@BalanceAmount,
    inactive: $.@Inactive,
    noOfAccounts: $.@NoOfAccounts,
    address: $.Addresses.*Address map (value,index)->{
       
    }
    
 }

However I have not been able to convert the Addresses element ( which contains multiple Address elements into a string array like this :

"address": [
          "LMN","QWE"
        ]

Am struggling with the last part , any ideas ?


Solution

  • Note that XML does not has the concept of an array. Addresses is just an element that has several address child elements.

    You can use the multivalued selector directly. It will return an array of the matching keys values. Map is only needed if you want to further transform each element.

    $.Addresses.*Address