如何用DataWeave生成指定结构的SOAP XML?
生成指定SOAP XML的DataWeave代码
需求目标
需要生成如下结构的SOAP XML,其中<Authenticated>字段的值根据输入payload的login字段动态设置:
<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xsi:xsd="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <AuthenticateResult xmlns="urn:authentication.soap.sforce.com"> <Authenticated>true</Authenticated> </AuthenticateResult> </soapenv:Body> </soapenv:Envelope>
输入payload:
{ "login": "true" }
原尝试代码
%dw 2.0 output application/xml ns soapenv http://schemas.xmlsoap.org/soap/envelope/ ns xsi http://www.w3.org/2001/XMLSchema-instance --- { soapenv#Envelope @(xsi#xsd:"http://schemas.xmlsoap.org/soap/envelope/"): { soapenv#Body: { AuthenticateResult @(xmlns: "urn:authentication.soap.sforce.com"): { Authenticated: payload.login } } } }
修正后的代码
%dw 2.0 output application/xml ns soapenv http://schemas.xmlsoap.org/soap/envelope/ ns xsi http://www.w3.org/2001/XMLSchema-instance var targetNs = "urn:authentication.soap.sforce.com" // 声明自定义变量 --- { soapenv#Envelope @( xmlns#soapenv: "http://schemas.xmlsoap.org/soap/envelope/", xmlns#xsi: "http://www.w3.org/2001/XMLSchema-instance", xsi#xsd: "http://schemas.xmlsoap.org/soap/envelope/" ): { soapenv#Body: { (targetNs)#AuthenticateResult: { // 使用命名空间前缀方式更规范 Authenticated: payload.login as Boolean default false // 可选:将字符串转布尔值,适配XML的布尔表现 } } } }
关键说明
- DataWeave完全支持
ns语法来声明XML命名空间,语法为ns 前缀 命名空间URI。 - 声明自定义变量使用
var 变量名 = 值的语法,比如示例中的targetNs,方便统一维护命名空间URI。 - 原代码中
<AuthenticateResult>的命名空间使用@(xmlns)方式虽然可行,但使用命名空间#元素名的方式更符合DataWeave处理XML命名空间的规范,能避免潜在的命名冲突。 - 如果需要将输入的字符串类型
login值转换为布尔类型,可以使用as Boolean,同时添加default false处理空值或非法输入的情况。
内容的提问来源于stack exchange,提问作者Jordan M
相关产品推荐
相关产品推荐

