Anurag Sharma
Anurag Sharma

Reputation: 935

Import xml namespace from custom Dataweave module

I'm trying to create a custom Dataweave module for centralizing my custom XML namespaces.

I followed the official document of Mulesoft:https://docs.mulesoft.com/mule-runtime/4.3/dataweave-create-module

it states that: "When you import a custom module into another DataWeave script, any functions, variables, types, and namespaces defined in the module become available for use in the DataWeave body".

So I was expecting that I could create a module (in modules folder) containing my namespaces like this: Namespaces.dwl

ns myNs1 http://namespaces/my1
ns myNs2 http://namespaces/my2

import that module in another Dataweave like this:

%dw 2.0
import * from modules::Namespaces
output application/java
---
{
    body: {
        myNs1#Response: {
            outcome: 'ACCEPTED'
        }
    } write "application/xml"
}

But I got this error:

The prefix myNs1 has not been previously declared using ns

I'm running on Mule 4.3.0

Upvotes: 1

Views: 741

Answers (2)

Vish
Vish

Reputation: 384

Tried this with With Mule 4 Runtime 4.4.0

It worked without any issues.

Created a custom module and declared namespaces and imported it into my dataweave worked without declaring prefixes again in the local dataweave.

Created below module under the folder src/main/resources/modules

Namespaces.dwl

ns myNs1 http://namespaces/my1
ns myNs2 http://namespaces/my2

Dataweave :

%dw 2.0
import * from modules::Namespaces
output application/java
---
{
    body: {
        myNs1#Response: {
            outcome: 'ACCEPTED'
        }
    } write "application/xml"
}

Upvotes: 0

oim
oim

Reputation: 1151

As aled have pointed out, it might have been a bug or incorrect information in the docs. From what I can see, the namespaces are properly imported but it seems that prefixes are expected to be declared locally.

You can use below:

%dw 2.0
import * from modules::Namespaces
output application/java

var myNs1Local = myNs1 as Namespace

---
{

    body: {
        myNs1Local#Response: {
            outcome: 'ACCEPTED'
        }
    } write "application/xml"
}

which will result to the expected output.

{
  body: "<?xml version='1.0' encoding='UTF-8'?>\n<myNs1:Response xmlns:myNs1=\"http://namespaces/my1\">\n  <outcome>ACCEPTED</outcome>\n</myNs1:Response>" as String {class: "java.lang.String"}
} as Object {encoding: "UTF-8", mediaType: "*/*", mimeType: "*/*", class: "java.util.LinkedHashMap"}

Notice here that what I used as the prefix is the declared variable (myNs1Local) but it still write the prefix as referenced in Namespace.dwl

Upvotes: 1

Related Questions