0
votes

Input XML

<Address>
    <Street>Street Line 1</Street>
    <Street>Street Line 2</Street>
    <Street>Street Line 3</Street>
    <City>City</City>
    <Postcode>0000</Postcode>
</Address>

Output XML Required

<DeliveryAddress>
    <DA1>Street Line 1</DA1>
    <DA2>Street Line 2</DA2>
    <DA3>Street Line 3</DA3>
    <City>City</City>
    <Postcode>0000</Postcode>
</DeliveryAddress>

How can I use Dataweave to put each street element to a particular DA element in the outbound XML?

I've tried to use a *wildcard (Address.*Street) however this then puts the Street elements as a child element:

<DeliveryAddress>
    <DA1>
        <Street>Street 1</Street>
        <Street>Street 2</Street>
        <Street>Street 3</Street>
    </DA1>
    <City>City</City>
    <Postcode>0000</Postcode>
</DeliveryAddress>

Please help ^_^

3

3 Answers

1
votes

The * wildcard is used to reference repeated elements, especially in XML format. Start from this point we can sequentially solve this problem:

  1. Start from this expression payload.Address.*Street we will get a list of Street.
  2. However, an error will occur if we directly use it in current DataWeave expression. Therefore wrap that expression inside a bracket: (payload.Address.*Street) to make it as an object instead of an array.
  3. Now we just need to rename the Street tag to the correspond DA(n). Hence we can utilize map operator to iterate each record, and use brackets or quote marks, () or '' or "" to enclose the keys of the output:

("DA" ++ $$ + 1) or "DA$($$ + 1)" are both equally returning the same result: DA1, DA2, DA3, ...

Therefore, the complete expression for this field should be: (payload.Address.*Street map { ("DA" ++ $$ + 1): $ })

0
votes

Based on Suthony input i just replicated below you can find the dwl script

%dw 1.0

%output application/xml

DeliveryAddress:{

(payload.Address.*Street map { 
    ("DA" ++ $$ + 1): $
}),
    city:payload.Address.City,
    PostCode:payload.Address.Postcode

}

Cheers!

0
votes
{
    DeliveryAddress: {
        (payload.Address.*Street map {
            ("DA" ++ $$ +1): $
        }),
        City: payload.Address.City,
        Postcode: payload.Address.Postcode
    }
}
  1. Use map to iterate over Street element
  2. ("DA" ++ $$+1) to print DA1, DA2 and so on.