DataWeave 2.0 – Output an XML with multiple elements

DataWeave 2.0 – Output an XML with multiple elements

Problem Description:

With DataWeave 2.0 I can output a simple XML – the following code:

%dw 2.0
output application/xml

---
a:
b:
c: "content"

Would output:

<?xml version='1.0' encoding='UTF-8'?>
<a>
  <b>
    <c>content</c>
  </b>
</a>

But what if I want multiple elements under the b tag, such as:

<?xml version='1.0' encoding='UTF-8'?>
<a>
  <b>
    <c>content</c>
    <d>dontent</d>
  </b>
</a>

I tried to use:

%dw 2.0
output application/xml

---
a:
b:
c: "content",
d: "dontent"

And I got the following error:

Invalid input ‘,’, expected ???

I also tried to just add d without the comma after c, but it didn’t work, either.

How can it be achieved?

I couldn’t find anything like it in the documentation or in the tutorial. Is there a way to get the XML I want without converting from JSON or any other type?

Solution – 1

You can try this with ++ concantentation

%dw 2.0
output application/xml
---
a:
b:((c: "content")++("d": "dontent"))

Output

<?xml version='1.0' encoding='UTF-8'?>
<a>
  <b>
    <c>content</c>
    <d>dontent</d>
  </b>
</a>

Solution – 2

You are not explicitly telling DataWeave the structure that you want so it surprising to even get any output at all. Use the curly braces to delimit objects. b is a key inside a, so the script should reflect that:

%dw 2.0
output application/xml
---
{
    a: {
        b: {
            c: "content",
            d: "dontent"
        }
    }
}

Output:

<?xml version='1.0' encoding='UTF-8'?>
<a>
  <b>
    <c>content</c>
    <d>dontent</d>
  </b>
</a>
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject