Skip to content
ENG

Attribute selector

Given the following input payload:

<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
</catalog>

Write a DataWeave transformation that produces the following output:

<?xml version='1.0' encoding='UTF-8'?>
<book>
<id>bk102</id>
<title>Midnight Rain</title>
<author>Ralls, Kim</author>
</book>

Optional:

  • Use a variable to hold the book you want and then use it in the Script.
  • Note that in this case the output is XML, so there always has to be a key/tag wrapping the whole object.
  • This exercise asks for the second book, but the book tags are repeated. Remember that you can use the multiple selector .* and the index selector [<n>] to get the expected value.
  • To get an attribute value that lives inside a tag, you can use the attribute selector .@.

🔒🔓Show solution
%dw 2.0
output application/xml
var book: Object = payload.catalog.*book[1]
---
book: {
id: book.@id,
title: book.title,
author: book.author
}
/* Without the variable:
book: {
id: payload.catalog.*book[1].@id,
title: payload.catalog.*book[1].title,
author: payload.catalog.*book[1].author
} */
{Code mat;}

Learn MuleSoft: courses, exercises and quizzes. Free, no sign-up.