Other ways to add default namespaces in Dataweave 2.0?

Viewed 455

I recently figured out how to add default namespaces in XML by consulting this doc page.

%dw 2.0
output application/xml
var dns = {uri: "http://api.acme.com/customer", prefix: ""} as Namespace
---
dns#customer: {
    dns#name: "Max",
    dns#city: "LA"
}

Which generates the following xml:

<?xml version='1.0' encoding='UTF-8'?>
<customer xmlns="http://api.acme.com/customer">
  <name>Max</name>
  <city>LA</city>
</customer>

Is there any other way using the ns declaration? Any documentation on the Namespace type? I can't find any.

1 Answers

Its a fairly simple type, probably defined something like this:

%dw 2.0
type Namespace = {
   URI: String,
   prefix: String
}

The Namespace is only really used with XML and has fairly basic information with it. I have a few 'recipes' I use, like something that recursively appends namespaces:

%dw 2.0

fun appendNamespace(data, nsSelector: (k: Key) -> Namespace | Null) =
  data match {
    case is Array -> data map appendNamespace($, nsSelector)
    case is Object -> data mapObject do {
      var ns0 = nsSelector($$)
      ---
      if (ns0 != null) ns0#"$($$)": appendNamespace($, nsSelector)
      else ($$): appendNamespace($, nsSelector)
    }
    else -> data
}

Used like this:

%dw 2.0

ns soapenv http://schemas.xmlsoap.org/soap/envelope/
ns tem http://tempuri.org/

output application/xml
---
{
    soapenv#Envelope: {
        soapenv#Header: null,
        soapenv#Body: payload appendNamespace tem
    }
}

And then of course there is the namespace selector (payload.someKey.#) which returns the Namespace object for that key. Beyond that, I've seen no other real use cases around it or useful ways to interact with it. Would be interesting to see someone post something else with more use, but thats all I got.

Related