Home > Enterprise >  DataWeave 2.0 - Output an XML with multiple elements
DataWeave 2.0 - Output an XML with multiple elements

Time:12-06

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?

CodePudding user response:

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>

CodePudding user response:

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>
  • Related