Mulesoft DataWeave为XML属性设置命名空间语法咨询
如何用DataWeave 1.0生成带命名空间属性的SOAP XML请求
问题描述
我正尝试构建包含命名空间属性的XML请求,想知道正确的语法来生成合规的XML。目标XML示例如下:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema"> <soapenv:Header/> <soapenv:Body> <Request> <soapenv:age ns1:type="ns2:string">1234</soapenv:age> </Request> </soapenv:Body> </soapenv:Envelope>
我现有的DataWeave代码写法有问题,没法生成正确的结果:
%dw 1.0 %output application/xml { ns1#age @(ns1#type: "ns2#string"): "1234" }
恳请指导正确的实现语法。
解决方案
要生成符合要求的SOAP XML,你需要在DataWeave中正确声明命名空间,并按照规则编写带命名空间的元素和属性。下面是完整的正确实现:
1. 完整的DataWeave 1.0代码
%dw 1.0 %output application/xml %namespace soapenv http://schemas.xmlsoap.org/soap/envelope/ %namespace ns1 http://www.w3.org/2001/XMLSchema-instance %namespace ns2 http://www.w3.org/2001/XMLSchema --- soapenv#Envelope: { soapenv#Header: {}, soapenv#Body: { Request: { soapenv#age @(ns1#type: ns2#string): "1234" } } }
2. 关键语法细节解释
- 命名空间声明:用
%namespace关键字在DataWeave头部定义每个命名空间的前缀与对应URI,后续就能通过前缀#元素名的方式便捷引用,不用重复写完整URI。 - 带命名空间的元素:比如
soapenv#Envelope、soapenv#age,用#分隔前缀和元素名,对应XML中的<soapenv:Envelope>、<soapenv:age>标签。 - 带命名空间的属性:属性部分
@(ns1#type: ns2#string)里,ns1#type对应XML中的ns1:type属性;属性值ns2#string不需要手动加引号,DataWeave会自动处理成XML中合规的ns2:string格式。 - 层级结构匹配:必须逐层构建Envelope、Header、Body、Request这些节点,确保和目标XML的层级完全一致。
3. 生成的最终XML输出
执行上述代码后,会精准生成你需要的合规SOAP XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema"> <soapenv:Header/> <soapenv:Body> <Request> <soapenv:age ns1:type="ns2:string">1234</soapenv:age> </Request> </soapenv:Body> </soapenv:Envelope>
内容的提问来源于stack exchange,提问作者user3428616
相关产品推荐
相关产品推荐

