Contact Us 1-800-596-4880

Include XML Namespaces

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

You can define different namespaces in the header and then reference them on each tag. Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave 1.0 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

Starting in the Mule 4.2.1 release, DataWeave also supports dynamically generated namespace keys and attributes.

The following example uses:

  • ns for namespace definitions in the header

  • @ to define other attributes in an XML element

DataWeave
%dw 2.0
output application/xml
ns orders http://www.acme.com/shemas/Orders
ns stores http://www.acme.com/shemas/Stores
---
root:
    orders#orders: {
        stores#shipNodeId: "SF01",
        stores#shipNodeId @(shipsVia:"LA01"): "NY03"
    }
Output
<?xml version='1.0' encoding='UTF-8'?>
<root>
  <orders:orders xmlns:orders="http://www.acme.com/shemas/Orders">
    <stores:shipNodeId xmlns:stores="http://www.acme.com/shemas/Stores">SF01</stores:shipNodeId>
    <stores:shipNodeId xmlns:stores="http://www.acme.com/shemas/Stores" shipsVia="LA01">NY03</stores:shipNodeId>
  </orders:orders>
</root>

Dynamically Generated Namespace Values

Support starting in Mule version 4.2.1

Using input defined in the DataWeave variables, the DataWeave functions in the following example output values for namespace keys and attributes.

DataWeave
%dw 2.0
fun dynKeyNs(ns0: Namespace, value: Any) = { ns0#myDynKey: value }
fun dynAttrNs(ns0: Namespace, value: Any) = { myChildTag @(ns0#myDynAttribute: true): value }
var namespace1 = {uri: "http://acme.com", prefix: "ns0"} as Namespace
var namespace2 = {uri: "http://emca.com", prefix: "ns0"} as Namespace
output application/xml
---
root:

{
  mytagA: dynKeyNs(namespace1, "myTest1"),
  myTagB: dynKeyNs(namespace2, "myTest2"),
  myTagC: dynAttrNs(namespace1, "myTest1"),
  myTagD: dynAttrNs(namespace2, "myTest2")
}
Output
<?xml version='1.0' encoding='UTF-8'?>
<root>
  <mytagA>
    <ns0:myDynKey xmlns:ns0="http://acme.com">myTest1</ns0:myDynKey>
  </mytagA>
  <myTagB>
    <ns0:myDynKey xmlns:ns0="http://emca.com">myTest2</ns0:myDynKey>
  </myTagB>
  <myTagC>
    <myChildTag xmlns:ns0="http://acme.com" ns0:myDynAttribute="true">myTest1</myChildTag>
  </myTagC>
  <myTagD>
    <myChildTag xmlns:ns0="http://emca.com" ns0:myDynAttribute="true">myTest2</myChildTag>
  </myTagD>
</root>