Nav

DataWeave Examples

Introduction

Below are a series of examples that demonstrate various data transformation approaches expressed in DataWeave. DataWeave code is typically written inside the Transform Message component, which is accessible in Anypoint Studio.

To step through basic DataWeave use cases and exercises in actual Mule applications, see the DataWeave Quickstart Guide.
The DataWeave code shown in the examples is understood in the context of input/output metadata. The tabs below can be toggled to see the metadata structures that DataWeave leverages to get the transformations done.

Basic Transformation

This basic transformation shows you how you can easily map fields from input to output without requiring any special operations other than transforming XML to JSON. It also changes the order and names of some of the fields.

Note that this transform only deals with a single instance of the "order" data structure at a time. If you want to deal with a collection of several orders coming in a single Mule message, you’d have to resort to the map operator to sort through them, shown in the next example.

The DataWeave Quickstart Guide walks you this same transformation, showing you how you can create it automatically via the drag-and-drop UI. It then goes into tweaking the code to make it more interesting.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
%dw 1.0
%output application/json
---
{
        address1: payload.order.buyer.address,
        city: payload.order.buyer.city,
        country: payload.order.buyer.nationality,
        email: payload.order.buyer.email,
        name: payload.order.buyer.name,
        postalCode: payload.order.buyer.postCode,
        stateOrProvince: payload.order.buyer.state
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version='1.0' encoding='UTF-8'?>
<order>
  <product>
    <price>5</price>
    <model>Mulesoft Connect 2016</model>
  </product>
  <item_amount>3</item_amount>
  <payment>
    <payment-type>credit-card</payment-type>
    <currency>USD</currency>
    <installments>1</installments>
  </payment>
  <buyer>
    <email>mike@hotmail.com</email>
    <name>Michael</name>
    <address>Koala Boulevard 314</address>
    <city>San Diego</city>
    <state>CA</state>
    <postCode>1345</postCode>
    <nationality>USA</nationality>
  </buyer>
  <shop>main branch</shop>
  <salesperson>Mathew Chow</salesperson>
</order>
Output

    
             
          
1
2
3
4
5
6
7
8
9
{
  "address1": "Koala Boulevard 314",
  "city": "San Diego",
  "country": "USA",
  "email": "mike@hotmail.com",
  "name": "Michael",
  "postalCode": "1345",
  "stateOrProvince": "CA"
}

Using the map Operator

Follow along to see how to use the map operator. The as operator is also featured in this example. Take an XML list of books and use DataWeave to output a JSON version of the book list. It goes through each <book> element from the XML input, simply using the map operator.

You can ensure the transformation generates the correct type for each element by using the as operator (used for type coercion - see an as operator example).

Since JSON cannot accept duplicate keys, elements that are duplicated in the input, show the first of the keys on the output side.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
%dw 1.0
%output application/json
---
items: payload.books map {
      type: "book",
      price: $.price as :number,
      properties: {
        title: $.title,
        author: $.author,
        year: $.year as :number
      }
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{
    "books": [
      {
        "-category": "cooking",
        "title": {
          "-lang": "en",
          "#text": "Everyday Italian"
        },
        "author": "Giada De Laurentiis",
        "year": "2005",
        "price": "30.00"
      },
      {
        "-category": "children",
        "title": {
          "-lang": "en",
          "#text": "Harry Potter"
        },
        "author": "J K. Rowling",
        "year": "2005",
        "price": "29.99"
      },
      {
        "-category": "web",
        "title": {
          "-lang": "en",
          "#text": "XQuery Kick Start"
        },
        "author": [
          "James McGovern",
          "Per Bothner",
          "Kurt Cagle",
          "James Linn",
          "Vaidyanathan Nagarajan"
        ],
        "year": "2003",
        "price": "49.99"
      },
      {
        "-category": "web",
        "-cover": "paperback",
        "title": {
          "-lang": "en",
          "#text": "Learning XML"
        },
        "author": "Erik T. Ray",
        "year": "2003",
        "price": "39.95"
      }
    ]
}
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{
  "items": [
    {
      "type": "book",
      "price": 30.00,
      "properties": {
        "title": {
          "-lang": "en",
          "#text": "Everyday Italian"
        },
        "author": "Giada De Laurentiis",
        "year": 2005
      }
    },
    {
      "type": "book",
      "price": 29.99,
      "properties": {
        "title": {
          "-lang": "en",
          "#text": "Harry Potter"
        },
        "author": "J K. Rowling",
        "year": 2005
      }
    },
    {
      "type": "book",
      "price": 49.99,
      "properties": {
        "title": {
          "-lang": "en",
          "#text": "XQuery Kick Start"
        },
        "author": [
          "James McGovern",
          "Per Bothner",
          "Kurt Cagle",
          "James Linn",
          "Vaidyanathan Nagarajan"
        ],
        "year": 2003
      }
    },
    {
      "type": "book",
      "price": 39.95,
      "properties": {
        "title": {
          "-lang": "en",
          "#text": "Learning XML"
        },
        "author": "Erik T. Ray",
        "year": 2003
      }
    }
  ]
}

Remove Fields

In this example, the input contains sensitive information that should be removed. The transform replicates the inbound structure but uses a simple remove operator to take away specific key:value pairs.

The example goes through the whole set of elements in the input using the map operator.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
%dw 1.0
%output application/xml
---
users: {
      (payload.users map {
        user: {
        personal_information: $.personal_information - "ssn",
        login_information: $.login_information - "password"
        }
      })
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
&lt;users&gt;
    &lt;user&gt;
        &lt;personal_information&gt;
            &lt;first_name&gt;Emiliano&lt;/first_name&gt;
            &lt;middle_name&gt;Romoaldo&lt;/middle_name&gt;
            &lt;last_name&gt;Lesende&lt;/last_name&gt;
            &lt;ssn&gt;001-08-84382&lt;/ssn&gt;
        &lt;/personal_information&gt;
        &lt;login_information&gt;
            &lt;username&gt;3miliano&lt;/username&gt;
            &lt;password&gt;mypassword1234&lt;/password&gt;
        &lt;/login_information&gt;
    &lt;/user&gt;
    &lt;user&gt;
        &lt;personal_information&gt;
            &lt;first_name&gt;Mariano&lt;/first_name&gt;
            &lt;middle_name&gt;Toribio&lt;/middle_name&gt;
            &lt;last_name&gt;de Achaval&lt;/last_name&gt;
            &lt;ssn&gt;002-05-34738&lt;/ssn&gt;
        &lt;/personal_information&gt;
        &lt;login_information&gt;
            &lt;username&gt;machaval&lt;/username&gt;
            &lt;password&gt;mypassword4321&lt;/password&gt;
        &lt;/login_information&gt;
    &lt;/user&gt;
&lt;/users&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;users&gt;
  &lt;user&gt;
    &lt;personal_information&gt;
      &lt;first_name&gt;Emiliano&lt;/first_name&gt;
      &lt;middle_name&gt;Romoaldo&lt;/middle_name&gt;
      &lt;last_name&gt;Lesende&lt;/last_name&gt;
    &lt;/personal_information&gt;
    &lt;login_information&gt;
      &lt;username&gt;3miliano&lt;/username&gt;
    &lt;/login_information&gt;
  &lt;/user&gt;
  &lt;user&gt;
    &lt;personal_information&gt;
      &lt;first_name&gt;Mariano&lt;/first_name&gt;
      &lt;middle_name&gt;Toribio&lt;/middle_name&gt;
      &lt;last_name&gt;de Achaval&lt;/last_name&gt;
    &lt;/personal_information&gt;
    &lt;login_information&gt;
      &lt;username&gt;machaval&lt;/username&gt;
    &lt;/login_information&gt;
  &lt;/user&gt;
&lt;/users&gt;

Replace Values

In this example, the input contains the same sensitive information as in the previous one, but instead of entirely removing the key:value pairs that contain it, the values are replaced with the string. The transform replicates the inbound structure but uses a simple when operator to replace values when specific keys occur.

The example goes through the whole set of elements in the input using the map operator.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
%dw 1.0
%output application/xml
---
users: { (payload.users map {
    user: {
       personal_information: $.personal_information mapObject {
            ($$): $ unless $$ ~= "ssn" otherwise "****"
       },
       login_information: $.login_information mapObject {
          ($$): $ unless $$ ~= "password" otherwise "****"
       }
     }
}) }
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
&lt;users&gt;
    &lt;user&gt;
        &lt;personal_information&gt;
            &lt;first_name&gt;Emiliano&lt;/first_name&gt;
            &lt;middle_name&gt;Romoaldo&lt;/middle_name&gt;
            &lt;last_name&gt;Lesende&lt;/last_name&gt;
            &lt;ssn&gt;001-08-84382&lt;/ssn&gt;
        &lt;/personal_information&gt;
        &lt;login_information&gt;
            &lt;username&gt;3miliano&lt;/username&gt;
            &lt;password&gt;mypassword1234&lt;/password&gt;
        &lt;/login_information&gt;
    &lt;/user&gt;
    &lt;user&gt;
        &lt;personal_information&gt;
            &lt;first_name&gt;Mariano&lt;/first_name&gt;
            &lt;middle_name&gt;Toribio&lt;/middle_name&gt;
            &lt;last_name&gt;de Achaval&lt;/last_name&gt;
            &lt;ssn&gt;002-05-34738&lt;/ssn&gt;
        &lt;/personal_information&gt;
        &lt;login_information&gt;
            &lt;username&gt;machaval&lt;/username&gt;
            &lt;password&gt;mypassword4321&lt;/password&gt;
        &lt;/login_information&gt;
    &lt;/user&gt;
&lt;/users&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;users&gt;
  &lt;user&gt;
    &lt;personal_information&gt;
      &lt;first_name&gt;Emiliano&lt;/first_name&gt;
      &lt;middle_name&gt;Romoaldo&lt;/middle_name&gt;
      &lt;last_name&gt;Lesende&lt;/last_name&gt;
      &lt;ssn&gt;****&lt;/ssn&gt;
    &lt;/personal_information&gt;
    &lt;login_information&gt;
      &lt;username&gt;3miliano&lt;/username&gt;
      &lt;password&gt;****&lt;/password&gt;
    &lt;/login_information&gt;
  &lt;/user&gt;
  &lt;user&gt;
    &lt;personal_information&gt;
      &lt;first_name&gt;Mariano&lt;/first_name&gt;
      &lt;middle_name&gt;Toribio&lt;/middle_name&gt;
      &lt;last_name&gt;de Achaval&lt;/last_name&gt;
      &lt;ssn&gt;****&lt;/ssn&gt;
    &lt;/personal_information&gt;
    &lt;login_information&gt;
      &lt;username&gt;machaval&lt;/username&gt;
      &lt;password&gt;****&lt;/password&gt;
    &lt;/login_information&gt;
  &lt;/user&gt;
&lt;/users&gt;

Target an Attribute

This example shows you how to transform a JSON array of objects to XML. Each object represents a book and its attributes.

The map operator carries out the same steps for each element in the input array. Through the use of @, attributes are injected into the XML.

See Attribute selector expressions on how to select XML attributes in DataWeave.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
%dw 1.0
%output application/xml
---
{
  bookstore: { (payload map {
      book : {
      title @(lang: "en"): $.item.properties.title,
      year: $.item.properties.year,
      price: $.item.price,
      ($.item.properties.author map
      author @(loc: "US"): $)
    }
  }) }
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
[
  {
    "item": {
      "type": "book",
      "price": 30,
      "properties": {
        "title": "Everyday Italian",
        "author": [
          "Giada De Laurentiis"
        ],
        "year": 2005
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 29.99,
      "properties": {
        "title": "Harry Potter",
        "author": [
          "J K. Rowling"
        ],
        "year": 2005
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 49.99,
      "properties": {
        "title": "XQuery Kick Start",
        "author": [
          "James McGovern",
          "Per Bothner",
          "Kurt Cagle",
          "James Linn",
          "Vaidyanathan Nagarajan"
        ],
        "year": 2003
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 39.95,
      "properties": {
        "title": "Learning XML",
        "author": [
          "Erik T. Ray"
        ],
        "year": 2003
      }
    }
  }
]
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;bookstore&gt;
  &lt;book&gt;
    &lt;title lang="en"&gt;Everyday Italian&lt;/title&gt;
    &lt;year&gt;2005&lt;/year&gt;
    &lt;price&gt;30&lt;/price&gt;
    &lt;author loc="US"&gt;Giada De Laurentiis&lt;/author&gt;
  &lt;/book&gt;
  &lt;book&gt;
    &lt;title lang="en"&gt;Harry Potter&lt;/title&gt;
    &lt;year&gt;2005&lt;/year&gt;
    &lt;price&gt;29.99&lt;/price&gt;
    &lt;author loc="US"&gt;J K. Rowling&lt;/author&gt;
  &lt;/book&gt;
  &lt;book&gt;
    &lt;title lang="en"&gt;XQuery Kick Start&lt;/title&gt;
    &lt;year&gt;2003&lt;/year&gt;
    &lt;price&gt;49.99&lt;/price&gt;
    &lt;author loc="US"&gt;James McGovern&lt;/author&gt;
    &lt;author loc="US"&gt;Per Bothner&lt;/author&gt;
    &lt;author loc="US"&gt;Kurt Cagle&lt;/author&gt;
    &lt;author loc="US"&gt;James Linn&lt;/author&gt;
    &lt;author loc="US"&gt;Vaidyanathan Nagarajan&lt;/author&gt;
  &lt;/book&gt;
  &lt;book&gt;
    &lt;title lang="en"&gt;Learning XML&lt;/title&gt;
    &lt;year&gt;2003&lt;/year&gt;
    &lt;price&gt;39.95&lt;/price&gt;
    &lt;author loc="US"&gt;Erik T. Ray&lt;/author&gt;
  &lt;/book&gt;
&lt;/bookstore&gt;

Adding Optional Fields Based on a Condition

When mapping something to an XML format, you may want to add certain tags based on a condition. The mapping below only inserts the 'insurance' tag when it’s present in the input.

The example goes through the whole set of elements in the input using a map operator. It also uses the when operator to only select instances that include the field 'insurance'.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
%dw 1.0
%output application/xml
---
users: {
  (payload map {
        user: {
          name: $.name,
          (insurance: $.insurance) when $.insurance?
        }
    })
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
[
  {
    "name" : "Julian",
    "gender" : "Male",
    "age" : 41,
    "insurance": "Osde"
  },
  {
    "name" : "Mariano",
    "gender" : "Male",
    "age" : 33
  }
]
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
&lt;?xml version='1.0' encoding='US-ASCII'?&gt;
&lt;users&gt;
  &lt;user&gt;
    &lt;name&gt;Julian&lt;/name&gt;
    &lt;insurance&gt;Osde&lt;/insurance&gt;
  &lt;/user&gt;
  &lt;user&gt;
    &lt;name&gt;Mariano&lt;/name&gt;
  &lt;/user&gt;
&lt;/users&gt;

Rename Keys When These Exist

This example takes in a JSON object that contains several fields. Most of them must be kept identical, except for a couple that optionally might appear in the payload, and if so should be renamed. Instead of referencing each field individually, this example renames two fields in particular and handles the rest without any changes.

The example goes through the whole set of elements in the input using a mapObject operator. Note that it differs from the map operation in that map object processes both key and value of its input, rather than just the keys. It also uses the when operator together with an and to pick out the specific keys that need to change, and an example use of the as operator to coerce its type to string.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
%dw 1.0
%output application/json
---
payload map {
($ mapObject {
    (emptySeats: $) when $$ as :string == 'availableSeats',
    (airline: $) when $$ as :string == 'airlineName',
    (($$):$) when ($$ as :string !='availableSeats') and ($$ as :string != 'airlineName')
  })
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
{
"flight":{
  "availableSeats":45,
  "airlineName":"Ryan Air",
  "aircraftBrand":"Boeing",
  "aircraftType":"737",
  "departureDate":"12/14/2015",
  "origin":"BCN",
  "destination":"FCO"
  }
}
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
[
  {
    "emptySeats": 45,
    "airline": "Ryan Air",
    "aircraftBrand": "Boeing",
    "aircraftType": "737",
    "departureDate": "12/14/2015",
    "origin": "BCN",
    "destination": "FCO"
  }
]

Using Constant Directives

This example converts an XML input to a JSON output that is structured differently and that contains URL links that are built from concatenating input content defining a few constant directives in The DataWeave Header. The transform also creates a few fields that are conditional and are only present in the output when they exist in the input.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
%dw 1.0
%output application/json
%var baseUrl="http://alainn-cosmetics.cloudhub.io/api/v1.0/"
%var urlPage="http://alainn-cosmetics.cloudhub.io/api/v1.0/items"
%var pageIndex=0
%var requestedPageSize=4
%var fullUrl="http://alainn-cosmetics.cloudhub.io/api/v1.0/items"
---
using (pageSize = payload.getItemsResponse.PageInfo.pageSize) {
     links: [
        {
            href: fullUrl,
            rel : "self"
        },
        {
            href: urlPage ++ "?pageIndex=" ++ (pageIndex + pageSize) ++ "&pageSize=" ++ requestedPageSize,
            rel: "next"
        },
        ({
            href: urlPage ++ "?pageIndex=" ++ (pageIndex - pageSize) ++ "&pageSize=" ++ requestedPageSize,
            rel: "prev"
        }) when (pageIndex > 0)
     ],
     collection: {
        size: pageSize,
        items: payload.getItemsResponse.*Item map {
            id: $.id,
            type: $.type,
            name: $.name,
            (summary: $.summary) when $.summary?,
            (brand: $.brand) when $.brand?,
            links: ($.images.*image map {
                href: trim $,
                rel: $.@type
            }) + {
                href: baseUrl ++ "/" ++ $.id,
                rel: "self"
            }
        }
     }
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
&lt;ns0:getItemsResponse xmlns:ns0="http://www.alainn.com/SOA/message/1.0"&gt;
    &lt;ns0:PageInfo&gt;
        &lt;pageIndex&gt;0&lt;/pageIndex&gt;
        &lt;pageSize&gt;20&lt;/pageSize&gt;
    &lt;/ns0:PageInfo&gt;
    &lt;ns1:Item xmlns:ns1="http://www.alainn.com/SOA/model/1.0"&gt;
        &lt;id&gt;B0015BYNRO&lt;/id&gt;
        &lt;type&gt;Oils&lt;/type&gt;
        &lt;name&gt;Now Foods LANOLIN PURE&lt;/name&gt;
        &lt;images&gt;
            &lt;image type="SwatchImage"&gt;http://ecx.images-amazon.com/images/I/11Qoe774Q4L._SL30_.jpg
            &lt;/image&gt;
        &lt;/images&gt;
    &lt;/ns1:Item&gt;
    &lt;ns1:Item xmlns:ns1="http://www.alainn.com/SOA/model/1.0"&gt;
        &lt;id&gt;B002K8AD02&lt;/id&gt;
        &lt;type&gt;Bubble Bath&lt;/type&gt;
        &lt;name&gt;Deep Steep Honey Bubble Bath&lt;/name&gt;
        &lt;summary&gt;Disclaimer: This website is for informational purposes only.
            Always check the actual product label in your possession for the most
            accurate ingredient information due to product changes or upgrades
            that may not yet be reflected on our web site. These statements made
            in this website have not been evaluated by the Food and Drug
            Administration. The products offered are not intended to diagnose,
            treat
        &lt;/summary&gt;
        &lt;images&gt;
            &lt;image type="SwatchImage"&gt;http://ecx.images-amazon.com/images/I/216ytnMOeXL._SL30_.jpg
            &lt;/image&gt;
        &lt;/images&gt;
    &lt;/ns1:Item&gt;
    &lt;ns1:Item xmlns:ns1="http://www.alainn.com/SOA/model/1.0"&gt;
        &lt;id&gt;B000I206JK&lt;/id&gt;
        &lt;type&gt;Oils&lt;/type&gt;
        &lt;name&gt;Now Foods Castor Oil&lt;/name&gt;
        &lt;summary&gt;One of the finest natural skin emollients available&lt;/summary&gt;
        &lt;images&gt;
            &lt;image type="SwatchImage"&gt;http://ecx.images-amazon.com/images/I/21Yz8q-yQoL._SL30_.jpg
            &lt;/image&gt;
        &lt;/images&gt;
    &lt;/ns1:Item&gt;
    &lt;ns1:Item xmlns:ns1="http://www.alainn.com/SOA/model/1.0"&gt;
        &lt;id&gt;B003Y5XF2S&lt;/id&gt;
        &lt;type&gt;Chemical Hair Dyes&lt;/type&gt;
        &lt;name&gt;Manic Panic Semi-Permanent Color Cream&lt;/name&gt;
        &lt;summary&gt;Ready to use, no mixing required&lt;/summary&gt;
        &lt;images&gt;
            &lt;image type="SwatchImage"&gt;http://ecx.images-amazon.com/images/I/51A2FuX27dL._SL30_.jpg
            &lt;/image&gt;
        &lt;/images&gt;
    &lt;/ns1:Item&gt;
    &lt;ns1:Item xmlns:ns1="http://www.alainn.com/SOA/model/1.0"&gt;
        &lt;id&gt;B0016BELU2&lt;/id&gt;
        &lt;type&gt;Chemical Hair Dyes&lt;/type&gt;
        &lt;name&gt;Herbatint Herbatint Permanent Chestnut (4n)&lt;/name&gt;
        &lt;images&gt;
            &lt;image type="SwatchImage"&gt;http://ecx.images-amazon.com/images/I/21woUiM0BdL._SL30_.jpg
            &lt;/image&gt;
        &lt;/images&gt;
    &lt;/ns1:Item&gt;
&lt;/ns0:getItemsResponse&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
{
  "links": [
    {
      "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/items",
      "rel": "self"
    },
    {
      "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/items?pageIndex=20&amp;pageSize=4",
      "rel": "next"
    }
  ],
  "collection": {
    "size": "20",
    "items": [
      {
        "id": "B0015BYNRO",
        "type": "Oils",
        "name": "Now Foods LANOLIN PURE",
        "links": [
          {
            "href": "http:\/\/ecx.images-amazon.com\/images\/I\/11Qoe774Q4L._SL30_.jpg",
            "rel": "SwatchImage"
          },
          {
            "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/\/B0015BYNRO",
            "rel": "self"
          }
        ]
      },
      {
        "id": "B002K8AD02",
        "type": "Bubble Bath",
        "name": "Deep Steep Honey Bubble Bath",
        "summary": "Disclaimer: This website is for informational purposes only.\n Always check the actual product label in your possession for the most\n accurate ingredient information due to product changes or upgrades\n that may not yet be reflected on our web site. These statements made\n in this website have not been evaluated by the Food and Drug\n Administration. The products offered are not intended to diagnose,\n treat\n ",
        "links": [
          {
            "href": "http:\/\/ecx.images-amazon.com\/images\/I\/216ytnMOeXL._SL30_.jpg",
            "rel": "SwatchImage"
          },
          {
            "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/\/B002K8AD02",
            "rel": "self"
          }
        ]
      },
      {
        "id": "B000I206JK",
        "type": "Oils",
        "name": "Now Foods Castor Oil",
        "summary": "One of the finest natural skin emollients available",
        "links": [
          {
            "href": "http:\/\/ecx.images-amazon.com\/images\/I\/21Yz8q-yQoL._SL30_.jpg",
            "rel": "SwatchImage"
          },
          {
            "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/\/B000I206JK",
            "rel": "self"
          }
        ]
      },
      {
        "id": "B003Y5XF2S",
        "type": "Chemical Hair Dyes",
        "name": "Manic Panic Semi-Permanent Color Cream",
        "summary": "Ready to use, no mixing required",
        "links": [
          {
            "href": "http:\/\/ecx.images-amazon.com\/images\/I\/51A2FuX27dL._SL30_.jpg",
            "rel": "SwatchImage"
          },
          {
            "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/\/B003Y5XF2S",
            "rel": "self"
          }
        ]
      },
      {
        "id": "B0016BELU2",
        "type": "Chemical Hair Dyes",
        "name": "Herbatint Herbatint Permanent Chestnut (4n)",
        "links": [
          {
            "href": "http:\/\/ecx.images-amazon.com\/images\/I\/21woUiM0BdL._SL30_.jpg",
            "rel": "SwatchImage"
          },
          {
            "href": "http:\/\/alainn-cosmetics.cloudhub.io\/api\/v1.0\/\/B0016BELU2",
            "rel": "self"
          }
        ]
      }
    ]
  }
}

Perform Basic Math

This example takes an XML input and parses it into a different XML arrangement. After a single <header> element is copied, a map operation carries out the same steps for each 'item': several fields are passed on without any changes, then the discount and subtotal fields are calculated with references to constants defined in the header directives of the transform. A single set of subtotal, tax and total elements are created by performing a reduce operation over all of the items in the "items" array, performing calculations that sometimes involve constants defined in the header. The as operator is also used to coerce to a number and then performs basic math on these numbers.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
%dw 1.0
%output application/xml
%var tax=0.085
%var discount=0.05
---
invoice: {
    header: payload.invoice.header,
    items: { (payload.invoice.items.*item map {
        item @(index: $$ + 1): {
            description: $.description,
            quantity: $.quantity,
            unit_price: $.unit_price,
            discount: (discount * 100) as :number { format: "##" } ++ "%",
            subtotal: $.unit_price * $.quantity * (1 - discount)
        }
    }) },
    totals: using (subtotal = payload.invoice.items reduce ((item, sum1 = 0) -> sum1 + (item.unit_price * item.quantity * (1 - discount)))) {
        subtotal: subtotal,
        tax: (tax * 100) as :number { format: "##.#" } ++ "%",
        total: subtotal * (1 + tax)
    }
}
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
&lt;invoice&gt;
    &lt;header&gt;
        &lt;customer_name&gt;ACME, Inc.&lt;/customer_name&gt;
        &lt;customer_state&gt;CA&lt;/customer_state&gt;
    &lt;/header&gt;
    &lt;items&gt;
        &lt;item&gt;
            &lt;description&gt;Product 1&lt;/description&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
            &lt;unit_price&gt;10&lt;/unit_price&gt;
        &lt;/item&gt;
        &lt;item&gt;
            &lt;description&gt;Product 2&lt;/description&gt;
            &lt;quantity&gt;1&lt;/quantity&gt;
            &lt;unit_price&gt;30&lt;/unit_price&gt;
        &lt;/item&gt;
    &lt;/items&gt;
&lt;/invoice&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;invoice&gt;
  &lt;header&gt;
    &lt;customer_name&gt;ACME, Inc.&lt;/customer_name&gt;
    &lt;customer_state&gt;CA&lt;/customer_state&gt;
  &lt;/header&gt;
  &lt;items&gt;
    &lt;item index="1"&gt;
      &lt;description&gt;Product 1&lt;/description&gt;
      &lt;quantity&gt;2&lt;/quantity&gt;
      &lt;unit_price&gt;10&lt;/unit_price&gt;
      &lt;discount&gt;5%&lt;/discount&gt;
      &lt;subtotal&gt;20&lt;/subtotal&gt;
    &lt;/item&gt;
    &lt;item index="2"&gt;
      &lt;description&gt;Product 2&lt;/description&gt;
      &lt;quantity&gt;1&lt;/quantity&gt;
      &lt;unit_price&gt;30&lt;/unit_price&gt;
      &lt;discount&gt;5%&lt;/discount&gt;
      &lt;subtotal&gt;30&lt;/subtotal&gt;
    &lt;/item&gt;
  &lt;/items&gt;
  &lt;totals&gt;
    &lt;subtotal&gt;47.5&lt;/subtotal&gt;
    &lt;tax&gt;8.5%&lt;/tax&gt;
    &lt;total&gt;51.5375&lt;/total&gt;
  &lt;/totals&gt;
&lt;/invoice&gt;

Group By

This example takes in an XML file that is grouped separating two types of elements: teachers and students, the transform uses the Group By operation to make it into an XML where the top level grouping is "class". Within each class, the students and teachers that are registered in it are listed.

The example goes through the whole set of elements in the input using both a map object operation and a map operation. Note that they differ in that map object processes both key and value of its input, rather than just the keys. It also uses the filter operation to only show the attendees that have the class subject listed as a hobby. As each student may have multiple hobbies, the Multi value selector is used to refer to them all.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%dw 1.0
%output application/dw
---
classrooms: payload.school.teachers groupBy $.subject mapObject ((teacherGroup, subject) -> {
    class: {
      name: subject,
      teachers: { (teacherGroup map {
        teacher:{
            name: $.name,
            lastName: $.lastName
        }
      }) },
      attendees: { (payload.school.students filter ($.*hobby contains subject) map {
        attendee: {
          name: $.name,
          lastName: $.lastName
        }
      }) }
    }
})
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
&lt;school&gt;
    &lt;teachers&gt;
        &lt;teacher&gt;
            &lt;name&gt;Mariano&lt;/name&gt;
            &lt;lastName&gt;De Achaval&lt;/lastName&gt;
            &lt;subject&gt;DW&lt;/subject&gt;
        &lt;/teacher&gt;
        &lt;teacher&gt;
            &lt;name&gt;Emiliano&lt;/name&gt;
            &lt;lastName&gt;Lesende&lt;/lastName&gt;
            &lt;subject&gt;DW&lt;/subject&gt;
        &lt;/teacher&gt;
        &lt;teacher&gt;
            &lt;name&gt;Leandro&lt;/name&gt;
            &lt;lastName&gt;Shokida&lt;/lastName&gt;
            &lt;subject&gt;Scala&lt;/subject&gt;
        &lt;/teacher&gt;
    &lt;/teachers&gt;
    &lt;students&gt;
        &lt;student&gt;
            &lt;name&gt;Peter&lt;/name&gt;
            &lt;lastName&gt;Parker&lt;/lastName&gt;
            &lt;hobby&gt;DW&lt;/hobby&gt;
            &lt;hobby&gt;Scala&lt;/hobby&gt;
        &lt;/student&gt;
        &lt;student&gt;
            &lt;name&gt;Homer&lt;/name&gt;
            &lt;lastName&gt;Simpson&lt;/lastName&gt;
            &lt;hobby&gt;Scala&lt;/hobby&gt;
        &lt;/student&gt;
    &lt;/students&gt;
&lt;/school&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{
  "classrooms": {
    "class": {
      "name": "DW",
      "teachers": [
        {
          "teacher": {
            "name": [
              "Mariano"
            ],
            "lastName": [
              "De Achaval"
            ]
          }
        },
        {
          "teacher": {
            "name": [
              "Emiliano"
            ],
            "lastName": [
              "Lesende"
            ]
          }
        }
      ],
      "attendees": [
        {
          "attendee": {
            "name": [
              "Peter"
            ],
            "lastName": [
              "Parker"
            ]
          }
        }
      ]
    },
    "class": {
      "name": "Scala",
      "teachers": [
        {
          "teacher": {
            "name": [
              "Leandro"
            ],
            "lastName": [
              "Shokida"
            ]
          }
        }
      ],
      "attendees": [
        {
          "attendee": {
            "name": [
              "Peter"
            ],
            "lastName": [
              "Parker"
            ]
          }
        },
        {
          "attendee": {
            "name": [
              "Homer"
            ],
            "lastName": [
              "Simpson"
            ]
          }
        }
      ]
    }
  }
}

Multiple Inputs

In this example, there are three different input JSON files, these three all arrive in one single Mule message, occupying the payload and two flow variables. The payload contains an array of book objects, one flow variable has a set of currency exchange rates, and the other one a query. The transform filters the first input using the conditions passed in the third input, then performs a map to deal with each remaining object separately. Within this map, it defines two variables: it and props. Through the use of @, attributes are added into the XML tags. A second map operation inside the first one calculates the price of each book for each of the currencies provided in the second input. Another map operation displays each element in the author array as a separate <author></author> tag.

See flow variables for how to access flow variables from the input and Attribute selector expressions for how to access XML attributes in DataWeave.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%dw 1.0
%output application/xml
---
books: {
  (payload filter $.item.properties.year > flowVars.filterParameter.publishedAfter map using (it = $.item, props = $.item.properties) {
    book @(year: props.year): {
      (flowVars.exchagneRate.USD map {
        price @(currency: $.currency): $.ratio * it.price
      }),
      title: props.title,
      authors: { (props.author map {
        author: $
      }) }
    }
  })
}

Input 1

Input 1 - Payload

     
              
           
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[
  {
    "item": {
      "type": "book",
      "price": 30,
      "properties": {
        "title": "Everyday Italian",
        "author": [
          "Giada De Laurentiis"
        ],
        "year": 2005
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 29.99,
      "properties": {
        "title": "Harry Potter",
        "author": [
          "J K. Rowling"
        ],
        "year": 2005
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 49.99,
      "properties": {
        "title": "XQuery Kick Start",
        "author": [
          "James McGovern",
          "Per Bothner",
          "Kurt Cagle",
          "James Linn",
          "Kurt Cagle",
          "Vaidyanathan Nagarajan"
        ],
        "year": 2003
      }
    }
  },
  {
    "item": {
      "type": "book",
      "price": 39.95,
      "properties": {
        "title": "Learning XML",
        "author": [
          "Erik T. Ray"
        ],
        "year": 2003
      }
    }
  }
]

Input 2

Input 2 - FlowVariable exchangeRate

     
              
           
1
2
3
4
5
6
7
{
  "USD": [
    {"currency": "EUR", "ratio":0.92},
    {"currency": "ARS", "ratio":8.76},
    {"currency": "GBP", "ratio":0.66}
  ]
}

Input 3

Input 3 - FlowVariable filterParamenter

     
              
           
1
2
3
{
  "publishedAfter": 2004
}
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;books&gt;
  &lt;book year="2005"&gt;
    &lt;price currency="EUR"&gt;27.6&lt;/price&gt;
    &lt;price currency="ARS"&gt;262.8&lt;/price&gt;
    &lt;price currency="GBP"&gt;19.8&lt;/price&gt;
    &lt;title&gt;Everyday Italian&lt;/title&gt;
    &lt;authors&gt;
      &lt;author&gt;Giada De Laurentiis&lt;/author&gt;
    &lt;/authors&gt;
  &lt;/book&gt;
  &lt;book year="2005"&gt;
    &lt;price currency="EUR"&gt;27.5908&lt;/price&gt;
    &lt;price currency="ARS"&gt;262.7124&lt;/price&gt;
    &lt;price currency="GBP"&gt;19.7934&lt;/price&gt;
    &lt;title&gt;Harry Potter&lt;/title&gt;
    &lt;authors&gt;
      &lt;author&gt;J K. Rowling&lt;/author&gt;
    &lt;/authors&gt;
  &lt;/book&gt;
&lt;/books&gt;

Remove XML Attributes

As a more advanced use case, you may want to remove specific attributes from within an XML tag that are known to contain sensitive data.

The example defines a function in the dataweave header and then calls it on the body. It goes through the whole set of elements in the input using a mapObject operator. Note that it differs from the map operation in that map object processes both key and value of its input, rather than just the keys. It also uses the when and otherwise operators to pick out only instances where an XML attribute exists, and to do nothing otherwise. It also uses the match operator.

See Attribute selector expressions for how to access XML attributes in DataWeave.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
12
%dw 1.0
%output application/dw
%var removeAttribute = (element,attrName) ->
element mapObject {
  ($$) @((($$.@ - attrName) when $$.@? otherwise {} ) ) : $ match {
    :object -> removeAttribute($, attrName),
    default -> $
  }
}
---

removeAttribute(payload, "password")
Input

    
             
          
1
2
3
4
&lt;users&gt;
  &lt;user username="Julian" password="1234"/&gt;
  &lt;user username="Mariano" password="4321"/&gt;
&lt;/users&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
{
  users @(): {
    user @(
      username: "Julian"
    ): "",
    user @(
      username: "Mariano"
    ): ""
  }
}

Output self-closing XML tags

When producing an output in XML, DataWeave by default outputs every value as enclosed between an opening and a closing tag:


         
      
1
2
3
4
5
  <parentElement>
    <emptyElement1>15</emptyElement1>
    <emptyElement2>1</emptyElement2>
    <emptyElement3>8</emptyElement3>
  </parentElement>

In case you have empty fields that don’t hold any values within, you might find that you instead want to output a single tag that self-closes. You can set the DW output directive so that your transform generates an output that follows this style for each case. You configure this by setting the inlineCloseOn property to "empty".

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
%dw 1.0
%output application/xml inlineCloseOn="empty"
---
{
  payload: payload
}
---

removeAttribute(payload, "password")

{ "parentElement":{

    "emptyElement1":{},
    "emptyElement2":{},
    "emptyElement13":{}
  }
}
 
       
Output

    
             
          
1
2
3
4
5
6
7
8
&lt;?xml version='1.0' encoding='US-ASCII'?&gt;
&lt;payload&gt;
  &lt;parentElement&gt;
    &lt;emptyElement1/&gt;
    &lt;emptyElement2/&gt;
    &lt;emptyElement13/&gt;
  &lt;/parentElement&gt;
&lt;/payload&gt;
See more XML reader and writer properties on DataWeave formats.

Configure CSV Reader

DataWeave supports CSV inputs and outputs, by configuring the reader and writer properties, you can adapt it to different conventions regarding separations, line breaks, etc. Other formats also allow for this kind of configuration. See Using DataWeave in Studio to learn how you can do this easily through the UI, or look at the DataWeave XML Reference for the required XML syntax. You can also see a full reference of the reader properties available with CSV format on DataWeave formats.

Reader properties are set as part of the XML dw:transform-message component, whilst writer properties are specified in the DataWeave code itself, as part of the output directive. You can see a full reference to the writer properties available with CSV format on DataWeave formats.

This example takes a CSV file that is formatted in a certain way (with ; as a separator) and outputs another CSV file that is formatted differently (with , as a separator, and all values quoted).

Example Transformation

XML

          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dw:transform-message metadata:id="ab7c919b-c57c-47da-a1e7-207a7e571341" doc:name="Transform Message">
     <dw:input-payload mimeType="application/csv" doc:sample="sample_data/list_csv.csv">
         <dw:reader-property name="header" value="false"/>
         <dw:reader-property name="separator" value=";"/>
     </dw:input-payload>
     <dw:set-payload>
       <![CDATA[
%dw 1.0
%output application/csv separator = "," , header = false, quoteValues = true
---
payload
      ]]>
    </dw:set-payload>
</dw:transform-message>

Note that the code above includes not just the DW transformation, but the XML of the Transform Message component that contains it, to display the reader properties configured in it.

Input

    
             
          
1
2
3
4
name;address;phone
George Harrisson; 1234 Abbey Road, London; 12341123
David Gilmour; 3434 Diamond st., Dark side of the moon; 12341234
Steven Wilson; 13/16 Raven st., Somewhere but not Here; 1234567
Output

    
             
          
1
2
3
4
"name","address","phone"
"George Harrisson"," 1234 Abbey Road, London"," 12341123"
"David Gilmour"," 3434 Diamond st., Dark side of the moon"," 12341234"
"Steven Wilson"," 13/16 Raven st., Somewhere but not Here"," 1234567"

Parse Dates with Different Separators

Suppose that you want to include a date field that admits using different characters as separators between the elements of the date, and want DataWeave to be able to parse them as if they all were the same. For this example, imagine that you want to accept these three formats:

  • 26-JUL-2016

  • 26/JUL/2016

  • 26.JUL.2016

To do this, you can normalize the input with the replace operator so that they all match a single pattern, and then turn the resulting string to a date with coerce to date.

To improve the clarity in your code, you can easily abstract the normalizing of your string into custom a function, declaring it only once on your DW header, and then using it as many times as necessary by simply referencing this function.

Example Transformation

This is what the function for this example would look like:

DataWeave

          
       
1
%function normalize(date) date replace "/" with "-" replace "." with "-"

You can declare this function on the header of a DW script and then simply call it from anywhere in the DW body. The example below shows the full DataWeave transform for doing this:

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
%dw 1.0
%output text/xml
%function normalize(date) date replace "/" with "-" replace "." with "-"
---
{
dates : {
date1: normalize("26-JUL-16") as :date {format: "d-MMM-yy"} as :string {format: "yyyy-MM-dd"},
date2: normalize("26/JUL/16") as :date {format: "d-MMM-yy"} as :string {format: "yyyy-MM-dd"},
date3: normalize("26.JUL.16") as :date {format: "d-MMM-yy"} as :string {format: "yyyy-MM-dd"}
  }
}

This example only deals with dates that use different separator characters, for a more advanced use case that deals with different date patterns, see Conditional Date Parsing

Conditional Date Parsing

Suppose that you want to include a date field that admits different formats, and want DataWeave to be able to parse each accordingly. For this example, imagine that you want to accept these three formats:

  • Sun, 06 Nov 1994 08:49:37 GMT = E, d LLL u H:m:s O

  • Sun Nov 6 08:49:37 1994 = cccc, d-LLL-u H:m:s O

  • Sunday, 06-Nov-94 08:49:37 GMT = E LLL d H:m:s u

Start out by writing a regular expression to match each of them:

  • Sun, 06 Nov 1994 08:49:37 GMT = /^[A-z][A-z][A-z],/

  • Sun Nov 6 08:49:37 1994 = /^[A-z][A-z][A-z]\s/

  • Sunday, 06-Nov-94 08:49:37 GMT = This will be the default

You can use these regular expressions in a DW function that first evaluates a string to see which regular expression it matches, and then converts it through the the corresponding operation. This function should do the following:

  1. Take the input string as argument

  2. Match it with regular expressions in order to determine which format it’s in

  3. Run the coerce to date operator with the corresponding properties

  4. Return a date time object

Example Transformation

This is what the function looks like:

DataWeave

          
       
1
%var parseDate = (dateStr) -> dateStr as :localdatetime {format: "E, d LLL u H:m:s O"} when (dateStr contains /^[A-z][A-z][A-z],/) otherwise (dateStr as :localdatetime {format: "E LLL d H:m:s u"} when (dateStr contains /^[A-z][A-z][A-z]\s/) otherwise dateStr as :localdatetime {format: "cccc, d-LLL-u H:m:s O"})

You can declare this function on the header of a DW script and then simply call it from anywhere in the DW body like so:

DataWeave

          
       
1
2
3
4
5
%dw 1.0
%output application/json
%var parseDate = (dateStr) -> dateStr as :localdatetime {format: "E, d LLL u H:m:s O"} when (dateStr contains /^[A-z][A-z][A-z],/) otherwise (dateStr as :localdatetime {format: "E LLL d H:m:s u"} when (dateStr contains /^[A-z][A-z][A-z]\s/) otherwise dateStr as :localdatetime {format: "cccc, d-LLL-u H:m:s O"})
---
date: parseDate(payload.dateString)

Create Mule Config

This example use of DataWeave does not take any input—​rather, it simply creates an XML structure out of hard-coded instructions, which reference several external sources using certain namespace directives. What you end up with is a set of XML tags mirroring the structure of a Mule application XML file, including attributes that go inside these tags through the use of @

See Attribute selector expressions for how to access XML attributes in DataWeave.

Example Transformation

DataWeave

     
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
%dw 1.0
%output application/xml encoding="UTF-8"
%namespace http http://www.mulesoft.org/schema/mule/http
%namespace as2 http://www.mulesoft.org/schema/mule/as2
%namespace spring http://www.springframework.org/schema/beans
%namespace doc http://www.mulesoft.org/schema/mule/documentation
%namespace sftp http://www.mulesoft.org/schema/mule/sftp
---

mule: {

  http#connector @(name:"HTTP_HTTPS",
                                  cookieSpec:"netscape",
                                  alidateConnections:"true",
                                sendBufferSize:"0",
                                receiveBufferSize:"0",
                                receiveBacklog:"0",
                                clientSoTimeout:"10000",
                                serverSoTimeout:"10000",
                                    socketSoLinger:"0",
                                doc#name:"HTTP-HTTPS"
  ): {},

  http#endpoint @(exchange-pattern:"request-response",
                                host:"localhost",
                                    port:"\${http.port}",
                                connector-ref:"HTTP_HTTPS",
                                method:"POST",
                                    name:"http-receive-endpoint",
                                doc#name:"HTTP"
  ): {},

  http#endpoint @(exchange-pattern:"request-response",
                                host:"btsci-dev.cloudapp.net",
                                    port:"80",
                                connector-ref:"HTTP_HTTPS",
                                method:"POST",
                                name:"http-send-endpoint",
                                    doc#name:"HTTP",
                                path:"as2tests/scenario1/BTSHTTPReceive.dll"
  ): {},

  as2#config @(name:"receive-as2-config",
                                 httpEndpointRef:"http-receive-endpoint",
                                     doc#name:"AS2"
  ): {},

  as2#config @(name:"send-as2-config",
                                httpEndpointRef:"http-send-endpoint",
                                    doc#name:"AS2"
  ): {},


  flow @(name:"receive-flow"): {

            as2#receive @(config-ref:"receive-as2-config",
                                  doc#name:"Receive EDI over AS2",
                                            keyStorePassword:"passw0rd",
                                  keyStorePath:"myPartner.p12"): {},
            sftp#outbound-endpoint @(exchange-pattern:"one-way",
                                            host:"dev.modusintegration.com",
                                  port:"22",
                                  responseTimeout:"10000",
                                            doc#name:"Save EDI doc",
                                  password:"pa\$\$w0rd",
                                  path:"/mule/inbox",
                                            user:"guest"): {}
  },

  flow @(name:"send-flow"):{
          sftp#inbound-endpoint @(host:"dev.modusintegration.com",
                            port:"22",
                    responseTimeout:"10000",
                    doc#name:"Read EDI doc",
                    password:"\$pa\$\$w0rd",
                            path:"/mule/outbox",
                    user:"guest"  ):{},

    as2#send @(config-ref:"send-as2-config",
                      as2From:"myPartner",
                            as2To:"myCompany",
                      doc#name:"Send EDI over AS2",
                      encrypt:"true",
                            keyStorePassword:"passw0rd",
                      keyStorePath:"myPartner.p12",
                      sign:"true"):{}
  }

}
Output

    
            
         
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:as2="http://www.mulesoft.org/schema/mule/as2"
      xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
      xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"&gt;
    &lt;http:connector name="HTTP_HTTPS" cookieSpec="netscape" alidateConnections="true" sendBufferSize="0" receiveBufferSize="0" receiveBacklog="0" clientSoTimeout="10000" serverSoTimeout="10000" socketSoLinger="0" doc:name="HTTP-HTTPS"&gt;&lt;/http:connector&gt;
    &lt;http:endpoint exchange-pattern="request-response" host="localhost" port="${http.port}" connector-ref="HTTP_HTTPS" method="POST" name="http-receive-endpoint" doc:name="HTTP"&gt;&lt;/http:endpoint&gt;
    &lt;http:endpoint exchange-pattern="request-response" host="btsci-dev.cloudapp.net" port="80" connector-ref="HTTP_HTTPS" method="POST" name="http-send-endpoint" doc:name="HTTP" path="as2tests/scenario1/BTSHTTPReceive.dll"&gt;&lt;/http:endpoint&gt;
    &lt;as2:config name="receive-as2-config" httpEndpointRef="http-receive-endpoint" doc:name="AS2"&gt;&lt;/as2:config&gt;
    &lt;as2:config name="send-as2-config" httpEndpointRef="http-send-endpoint" doc:name="AS2"&gt;&lt;/as2:config&gt;
    &lt;flow name="receive-flow"&gt;
        &lt;as2:receive config-ref="receive-as2-config" doc:name="Receive EDI over AS2" keyStorePassword="passw0rd" keyStorePath="myPartner.p12"&gt;&lt;/as2:receive&gt;
        &lt;sftp:outbound-endpoint exchange-pattern="one-way" host="dev.modusintegration.com" port="22" responseTimeout="10000" doc:name="Save EDI doc" password="pa$$w0rd" path="/mule/inbox" user="guest"&gt;&lt;/sftp:outbound-endpoint&gt;
    &lt;/flow&gt;
    &lt;flow name="send-flow"&gt;
        &lt;sftp:inbound-endpoint host="dev.modusintegration.com" port="22" responseTimeout="10000" doc:name="Read EDI doc" password="$pa$$w0rd" path="/mule/outbox" user="guest"&gt;&lt;/sftp:inbound-endpoint&gt;
        &lt;as2:send config-ref="send-as2-config" as2From="myPartner" as2To="myCompany" doc:name="Send EDI over AS2" encrypt="true" keyStorePassword="passw0rd" keyStorePath="myPartner.p12" sign="true"&gt;&lt;/as2:send&gt;
    &lt;/flow&gt;
&lt;/mule&gt;

Create Mule POM

This example does not take any input in, it simply creates an XML output out of hard-coded instruction. It references several external sources through namespace directives and defines a version as a constant in the header, that is then referenced in the body. It creates a set of XML tags that replicate the structure of a Mule POM file, including attributes inside these tags that are added through the use of @ and references to a variable.

See Attribute selector expressions for how to access XML attributes in DataWeave.

Example Transformation

DataWeave

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
%dw 1.0
%output application/xml
%namespace xsi http://www.w3.org/2001/XMLSchema-instance
%var modelVersion = "4.0.0"
---
{
    project: {

      modelVersion: modelVersion,
    groupId: "com.mycompany",
    version: "1.0.0-SNAPSHOT",
    packaging: "mule",
    name: "Mavenito",

    properties: {
        "project.build.sourceEncoding": "UTF-8",
      "project.reporting.outputEncoding": "UTF-8",
      "mule.version": "3.6.0",
      "mule.tools.version": "1.0"
    },

    build: {
        plugins: {
          plugin: {
            groupId: "org.mule.tools.maven",
          artifactId: "mule-app-maven-plugin",
          version: "\${mule.tools.version}",
          extensions: true,
          configuration: {
                        copyToAppsDirectory: true
          }
        },
        plugin: {
          artifactId: "maven-assembly-plugin",
                    version: "2.2.1",
                  configuration: {
                            descriptorRefs: {
                                descriptorRef: "project"
                }
             }
        },
        plugin: {
          groupId: "org.mojohaus",
                     artifactId: "build-helper-maven-plugin",
                    version:1.7,
                    executions: {
                            execution: {
                                id: "add-resource",
                                phase: "generate-resources",
                                goals: {
                                    goal: "add-resource"
                                },
                                configuration: {
                                        resources: {
                                            resource: {
                                                directory: "src/main/app/"
                                            },
                                            resource: {
                                                directory: "mappings/"
                      }
                                    }
                                }
                            },
                    configuration: {
                            resources: {
                 resource: {
                         directory: "src/main/api/"
                                    }
              }
          }
        }
      },
      plugin: {
          groupId: "org.apache.maven.plugins",
        artifcatId: "maven-dependency-plugin",
        version: "2.4",
        executions: {
              execution: {
                  id: "copy-clover-plugins",
              phase: "validate",
              goals: {
                  goal: "copy"
              },
              configuration: {
                 overWriteReleases: true,
                 overWriteSnapshots: true,
                 overWriteIfNewer: true,
                 stripVersion: true,
                 outputDirectory: "\${project.build.testOutputDirectory}"
              },
              artifactItems: {
                                artifactItem: {
                           groupId: "com.cloveretl",
                        artifactId: "cloveretl-engine",
                                        version: "\${mule.version}",
                                        type: "zip"
                    }
                 }
              }
        }
      },
      plugin: {
          artifactId: "maven-antrun-plugin",
                version: "1.7",
        executions: {
               execution: {
                        phase: "compile",
                        configuration: {
                            tasks: {
                                    unzip @(dest: "\${project.build.testOutputDirectory}",
                          src: "\${project.build.testOutputDirectory}/cloveretl-engine.zip"): {}
                        }
           },
           goals: {
                            goal: "run"
           }
         }
           }
      }
    }
  },

  dependencies: {
    dependency: {
        groupId: "com.mulesoft.muleesb",
      artifactId: "mule-core-ee",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "com.mulesoft.muleesb.modules",
      artifactId: "mule-module-spring-config-ee",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.transports",
      artifactId: "mule-transport-file",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.transports",
      artifactId: "mule-transport-http",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "com.mulesoft.muleesb.transports",
      artifactId: "mule-transport-jdbc-ee",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "com.mulesoft.muleesb.transports",
      artifactId: "mule-transport-jms-ee",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.transports",
      artifactId: "mule-transport-vm",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.modules",
      artifactId: "mule-module-scripting",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.modules",
      artifactId: "mule-module-xml",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "org.mule.tests",
      artifactId: "mule-tests-functional",
      version: "\${mule.version}",
      scope: "provided"
    },
    dependency: {
        groupId: "com.cloveretl",
      artifactId: "cloveretl-engine",
      version: "\${mule.version}",
      scope: "provided"
    }
    },

  repositories: {
      repository: {
        id: "Central",
      name: "Central",
      url: "http://repo1.maven.org/maven2/",
      layout: "default"
    },
    repository: {
        id: "mulesoft-releases",
      name: "MuleSoft Releases Repository",
      url: "http://repository.mulesoft.org/releases/",
      layout: "default"
    },
    repository: {
        id: "mulesoft-snapshots",
      name: "MuleSoft Snapshots Repository",
      url: "http://repository.mulesoft.org/snapshots/",
      layout: "default"
    }
  },


  pluginRepositories: {
    pluginRepository: {
                id: "mulesoft-release",
                name: "mulesoft release repository",
                layout: "default",
        url: "http://repository.mulesoft.org/releases/",
                 snapshots: {
                enabled: false
                }
    }
  }

 }
}
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;com.mycompany&lt;/groupId&gt;
  &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt;
  &lt;packaging&gt;mule&lt;/packaging&gt;
  &lt;name&gt;Mavenito&lt;/name&gt;
  &lt;properties&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
    &lt;mule.version&gt;3.6.0&lt;/mule.version&gt;
    &lt;mule.tools.version&gt;1.0&lt;/mule.tools.version&gt;
  &lt;/properties&gt;
  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.mule.tools.maven&lt;/groupId&gt;
        &lt;artifactId&gt;mule-app-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;${mule.tools.version}&lt;/version&gt;
        &lt;extensions&gt;true&lt;/extensions&gt;
        &lt;configuration&gt;
          &lt;copyToAppsDirectory&gt;true&lt;/copyToAppsDirectory&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.2.1&lt;/version&gt;
        &lt;configuration&gt;
          &lt;descriptorRefs&gt;
            &lt;descriptorRef&gt;project&lt;/descriptorRef&gt;
          &lt;/descriptorRefs&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.mojohaus&lt;/groupId&gt;
        &lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;1.7&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;add-resource&lt;/id&gt;
            &lt;phase&gt;generate-resources&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;add-resource&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
              &lt;resources&gt;
                &lt;resource&gt;
                  &lt;directory&gt;src/main/app/&lt;/directory&gt;
                &lt;/resource&gt;
                &lt;resource&gt;
                  &lt;directory&gt;mappings/&lt;/directory&gt;
                &lt;/resource&gt;
              &lt;/resources&gt;
            &lt;/configuration&gt;
          &lt;/execution&gt;
          &lt;configuration&gt;
            &lt;resources&gt;
              &lt;resource&gt;
                &lt;directory&gt;src/main/api/&lt;/directory&gt;
              &lt;/resource&gt;
            &lt;/resources&gt;
          &lt;/configuration&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifcatId&gt;maven-dependency-plugin&lt;/artifcatId&gt;
        &lt;version&gt;2.4&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;copy-clover-plugins&lt;/id&gt;
            &lt;phase&gt;validate&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;copy&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
              &lt;overWriteReleases&gt;true&lt;/overWriteReleases&gt;
              &lt;overWriteSnapshots&gt;true&lt;/overWriteSnapshots&gt;
              &lt;overWriteIfNewer&gt;true&lt;/overWriteIfNewer&gt;
              &lt;stripVersion&gt;true&lt;/stripVersion&gt;
              &lt;outputDirectory&gt;${project.build.testOutputDirectory}&lt;/outputDirectory&gt;
            &lt;/configuration&gt;
            &lt;artifactItems&gt;
              &lt;artifactItem&gt;
                &lt;groupId&gt;com.cloveretl&lt;/groupId&gt;
                &lt;artifactId&gt;cloveretl-engine&lt;/artifactId&gt;
                &lt;version&gt;${mule.version}&lt;/version&gt;
                &lt;type&gt;zip&lt;/type&gt;
              &lt;/artifactItem&gt;
            &lt;/artifactItems&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;
        &lt;version&gt;1.7&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;phase&gt;compile&lt;/phase&gt;
            &lt;configuration&gt;
              &lt;tasks&gt;
                &lt;unzip dest="${project.build.testOutputDirectory}" src="${project.build.testOutputDirectory}/cloveretl-engine.zip"&gt;&lt;/unzip&gt;
              &lt;/tasks&gt;
            &lt;/configuration&gt;
            &lt;goals&gt;
              &lt;goal&gt;run&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.mulesoft.muleesb&lt;/groupId&gt;
      &lt;artifactId&gt;mule-core-ee&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.mulesoft.muleesb.modules&lt;/groupId&gt;
      &lt;artifactId&gt;mule-module-spring-config-ee&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.transports&lt;/groupId&gt;
      &lt;artifactId&gt;mule-transport-file&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.transports&lt;/groupId&gt;
      &lt;artifactId&gt;mule-transport-http&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.mulesoft.muleesb.transports&lt;/groupId&gt;
      &lt;artifactId&gt;mule-transport-jdbc-ee&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.mulesoft.muleesb.transports&lt;/groupId&gt;
      &lt;artifactId&gt;mule-transport-jms-ee&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.transports&lt;/groupId&gt;
      &lt;artifactId&gt;mule-transport-vm&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.modules&lt;/groupId&gt;
      &lt;artifactId&gt;mule-module-scripting&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.modules&lt;/groupId&gt;
      &lt;artifactId&gt;mule-module-xml&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mule.tests&lt;/groupId&gt;
      &lt;artifactId&gt;mule-tests-functional&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.cloveretl&lt;/groupId&gt;
      &lt;artifactId&gt;cloveretl-engine&lt;/artifactId&gt;
      &lt;version&gt;${mule.version}&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
  &lt;repositories&gt;
    &lt;repository&gt;
      &lt;id&gt;Central&lt;/id&gt;
      &lt;name&gt;Central&lt;/name&gt;
      &lt;url&gt;http://repo1.maven.org/maven2/&lt;/url&gt;
      &lt;layout&gt;default&lt;/layout&gt;
    &lt;/repository&gt;
    &lt;repository&gt;
      &lt;id&gt;mulesoft-releases&lt;/id&gt;
      &lt;name&gt;MuleSoft Releases Repository&lt;/name&gt;
      &lt;url&gt;http://repository.mulesoft.org/releases/&lt;/url&gt;
      &lt;layout&gt;default&lt;/layout&gt;
    &lt;/repository&gt;
    &lt;repository&gt;
      &lt;id&gt;mulesoft-snapshots&lt;/id&gt;
      &lt;name&gt;MuleSoft Snapshots Repository&lt;/name&gt;
      &lt;url&gt;http://repository.mulesoft.org/snapshots/&lt;/url&gt;
      &lt;layout&gt;default&lt;/layout&gt;
    &lt;/repository&gt;
  &lt;/repositories&gt;
  &lt;pluginRepositories&gt;
    &lt;pluginRepository&gt;
      &lt;id&gt;mulesoft-release&lt;/id&gt;
      &lt;name&gt;mulesoft release repository&lt;/name&gt;
      &lt;layout&gt;default&lt;/layout&gt;
      &lt;url&gt;http://repository.mulesoft.org/releases/&lt;/url&gt;
      &lt;snapshots&gt;
        &lt;enabled&gt;false&lt;/enabled&gt;
      &lt;/snapshots&gt;
    &lt;/pluginRepository&gt;
  &lt;/pluginRepositories&gt;
&lt;/project&gt;

Pass Functions as Arguments

The following example makes all "keys" lower case. The DataWeave header defines a function that receives another function as an argument and then calls that function in the body, applying itself to the keys and not the values it processes. The function that is sent as an argument is a simple one that uses the lower operator to set the specified text to lower case.

The example goes through the whole set of elements in the input using a mapObject operator. It also uses the when and otherwise operators to pick out only instances when an XML attribute exists, and do nothing otherwise. It also uses the match operator.

See Attribute selector expressions on how to access XML attributes in DataWeave.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
%dw 1.0
%output application/xml
%function mapKeys(element, func)
  element match {
    obj is :object -> obj mapObject {
      "$(func($$))" @(($$.@ when $.@? otherwise {}) ): mapKeys($, func)
    },
    default -> element
  }
---
mapKeys(payload, ((key) ->(lower key)))
Input

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
&lt;CATALOG&gt;
  &lt;CD&gt;
    &lt;TITLE name="foo"&gt;Empire Burlesque&lt;/TITLE&gt;
    &lt;ARTIST&gt;Bob Dylan&lt;/ARTIST&gt;
    &lt;COUNTRY&gt;USA&lt;/COUNTRY&gt;
    &lt;COMPANY&gt;Columbia&lt;/COMPANY&gt;
    &lt;PRICE&gt;10.90&lt;/PRICE&gt;
    &lt;YEAR&gt;1985&lt;/YEAR&gt;
  &lt;/CD&gt;
  &lt;CD&gt;
    &lt;TITLE&gt;Hide your heart&lt;/TITLE&gt;
    &lt;ARTIST&gt;Bonnie Tyler&lt;/ARTIST&gt;
    &lt;COUNTRY&gt;UK&lt;/COUNTRY&gt;
    &lt;COMPANY&gt;CBS Records&lt;/COMPANY&gt;
    &lt;PRICE&gt;9.90&lt;/PRICE&gt;
    &lt;YEAR&gt;1988&lt;/YEAR&gt;
  &lt;/CD&gt;
&lt;/CATALOG&gt;
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
&lt;?xml version='1.0' encoding='US-ASCII'?&gt;
&lt;catalog&gt;
  &lt;cd&gt;
    &lt;title name="foo"&gt;Empire Burlesque&lt;/title&gt;
    &lt;artist&gt;Bob Dylan&lt;/artist&gt;
    &lt;country&gt;USA&lt;/country&gt;
    &lt;company&gt;Columbia&lt;/company&gt;
    &lt;price&gt;10.90&lt;/price&gt;
    &lt;year&gt;1985&lt;/year&gt;
  &lt;/cd&gt;
  &lt;cd&gt;
    &lt;title&gt;Hide your heart&lt;/title&gt;
    &lt;artist&gt;Bonnie Tyler&lt;/artist&gt;
    &lt;country&gt;UK&lt;/country&gt;
    &lt;company&gt;CBS Records&lt;/company&gt;
    &lt;price&gt;9.90&lt;/price&gt;
    &lt;year&gt;1988&lt;/year&gt;
  &lt;/cd&gt;
&lt;/catalog&gt;
----

Dynamic Mapping Based on a Definition

Based on a mapping definition, stored for instance in a DB table, you can dynamically execute a transformation. Here you have two inputs, one coming in via the payload, the other from a flowVariable called mapping.

  • The whole set of elements in the input is mapped using a map operator.

  • The example also uses the default operator.

Note that for this example to work, on the payload input you must set the reader configuration so that the 'nullValueOn' attribute is "empty". See reader configuration for instructions on how to set this.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
%dw 1.0
%output application/json
%var applyMapping = (input, mappingsDef) ->
{
  (mappingsDef map ((mappingDef) -> {
  (mappingDef.target) : input[mappingDef.source] default mappingDef.default
  }))
}
---
payload.sfdc_users.*sfdc_user map ((user) -> applyMapping(user, mapping))
Input - Payload

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
&lt;sfdc_users&gt;
    &lt;sfdc_user&gt;
      &lt;sfdc_name&gt;Mariano&lt;/sfdc_name&gt;
      &lt;sfdc_last_name&gt;Achaval&lt;/sfdc_last_name&gt;
      &lt;sfdc_employee&gt;true&lt;/sfdc_employee&gt;
    &lt;/sfdc_user&gt;
    &lt;sfdc_user&gt;
      &lt;sfdc_name&gt;Julian&lt;/sfdc_name&gt;
      &lt;sfdc_last_name&gt;Esevich&lt;/sfdc_last_name&gt;
      &lt;sfdc_employee&gt;true&lt;/sfdc_employee&gt;
    &lt;/sfdc_user&gt;
    &lt;sfdc_user&gt;
      &lt;sfdc_name&gt;Leandro&lt;/sfdc_name&gt;
      &lt;sfdc_last_name&gt;Shokida&lt;/sfdc_last_name&gt;
    &lt;/sfdc_user&gt;
&lt;/sfdc_users&gt;
Input - flowVariable Mapping

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[
  {
    "source": "sfdc_name",
    "target": "name",
    "default": "---"
  },
  {
    "source": "sfdc_last_name",
    "target": "lastName",
    "default": "---"
  },
  {
    "source": "sfdc_employee",
    "target": "user",
    "default": true
  }
]
Output

    
             
          
1
2
3
4
5
6
7
[
  {
    "name": "---",
    "lastName": "---",
    "user": true
  }
]

Conditional list reduction via a function

When presented with nested lists of data, you often need to flatten the data for a simplified output, extracting only the values required. Here you have a set of JSON data that returns a nested set of interests for a user and within are further nested sets. Certain values from the nested sets tags and contenttypes are needed to be extracted, with a conditional check to ensure contenttypes is present.

  • The whole set of elements in the input is mapped using a map operator.

  • This example uses the reduce operator.

  • This example also uses the when operator to conditionally display the last field.

  • This example also uses the splitBy operator to parse the input.

  • Finally this example takes advantage of the ability to define a function for re-use.

Example Transformation

DataWeave

          
       
1
2
3
4
5
6
7
8
9
10
11
%dw 1.0
%output application/json
%function reduceMapFor(data) data reduce (($$ splitBy ":")[0] ++ "," ++ ($ splitBy ":")[0])
---
payload.results map
        {
                email: $.profile.email,
                name: $.profile.firstName,
                 tags: reduceMapFor($.data.interests.tags[0]),
                 (contenttypes: reduceMapFor($.data.interests.contenttypes[0]))  when (sizeOf $.data.interests.contenttypes[0]) > 0
        }

Input - Payload


     
              
           
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{
  "results": [
    {
      "profile": {
        "firstName": "john",
        "lastName": "doe",
        "email": "johndoe@demo.com"
      },
      "data": {
        "interests": [
          {
            "language": "English",
            "tags": [
              "digital-strategy:Digital Strategy",
              "innovation:Innovation"
            ],
            "contenttypes": []
          }
        ]
      }
    },
    {
      "profile": {
        "firstName": "jane",
        "lastName": "doe",
        "email": "janedoe@demo.com"
      },
      "data": {
        "interests": [
          {
            "language": "English",
            "tags": [
              "tax-reform:Tax Reform",
              "retail-health:Retail Health"
            ],
            "contenttypes": [
              "News",
              "Analysis",
              "Case studies",
              "Press releases"
            ]
          }
        ]
      }
    }
  ],
  "objectsCount": 2,
  "totalCount": 2,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
Output

    
             
          
1
2
3
4
5
6
7
8
9
10
11
12
13
[
  {
    "email": "johndoe@demo.com",
    "name": "john",
    "tags": "digital-strategy,innovation"
  },
  {
    "email": "janedoe@demo.com",
    "name": "jane",
    "tags": "tax-reform,retail-health",
    "contenttypes": "News,Analysis,Case studies,Press releases"
  }
]