简体   繁体   中英

Mule Dataweave Repeating XML Elements to Individually Named XML Elements

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 ^_^

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): $ })

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!

{
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM