Free MuleSoft CONNECT Keynote & Expo Pass Available!

Register now+
Nav

Example: Inserting Attributes to an XML Tag

This example uses @(key:value) syntax (for example, @(loc: "US")) to inject attributes to XML tags. The example populates the "title" tag with two attributes, and each of the "author" tags with one too.

It uses these functions:

  • mapObject to go through each of the books in the input.

  • map to go through the authors in each book.

DataWeave

         
      
1
2
3
4
5
6
7
8
9
10
11
%dw 2.0
output application/xml
---
bookstore: payload.bookstore mapObject (book) -> {
      book : {
      title @(lang: "en", year: book.year): book.title,
      price: book.price,
      (book.*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
<?xml version='1.0' encoding='US-ASCII'?>
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <year>2005</year>
    <price>30</price>
    <author>Giada De Laurentiis</author>
  </book>
  <book>
    <title>Harry Potter</title>
    <year>2005</year>
    <price>29.99</price>
    <author>J K. Rowling</author>
  </book>
  <book>
    <title>XQuery Kick Start</title>
    <year>2003</year>
    <price>49.99</price>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
  </book>
  <book>
    <title>Learning XML</title>
    <year>2003</year>
    <price>39.95</price>
    <author>Erik T. Ray</author>
  </book>
</bookstore>
Output XML

         
      
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
<?xml version='1.0' encoding='US-ASCII'?>
<bookstore>
  <book>
    <title lang="en" year="2005">Everyday Italian</title>
    <price>30</price>
    <author loc="US">Giada De Laurentiis</author>
  </book>
  <book>
    <title lang="en" year="2005">Harry Potter</title>
    <price>29.99</price>
    <author loc="US">J K. Rowling</author>
  </book>
  <book>
    <title lang="en" year="2003">XQuery Kick Start</title>
    <price>49.99</price>
    <author loc="US">James McGovern</author>
    <author loc="US">Per Bothner</author>
    <author loc="US">Kurt Cagle</author>
    <author loc="US">James Linn</author>
    <author loc="US">Vaidyanathan Nagarajan</author>
  </book>
  <book>
    <title lang="en" year="2003">Learning XML</title>
    <price>39.95</price>
    <author loc="US">Erik T. Ray</author>
  </book>
</bookstore>

In this topic: