如何在DataWeave 2.0(Mule 4)中将XML转为单行格式?
Mule 4 DataWeave 2.0 实现XML压缩为单行无格式文本
需求说明
需将带有换行、空格、制表符的结构化XML,转换为无任何空白字符的单行XML,并包裹在{body: ...}的JSON结构中。
输入示例
<tns:ResponseMessage xmlns:n1="urn:sap-com:document:sap:rfc:functions" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"> <tns:Header> <tns:Verb>reply</tns:Verb> <tns:Noun>Compressed</tns:Noun> <tns:User/> <Signature xmlns=""> <SignedInfo> <CanonicalizationMethod Algorithm=""/> <SignatureMethod Algorithm=""/> </SignedInfo> <SignatureValue>XW8UqTTcR==</SignatureValue> <KeyInfo> <X509Data> <X509IssuerSerial> <X509IssuerName></X509IssuerName> <X509SerialNumber>1448033456</X509SerialNumber> </X509IssuerSerial> <X509SubjectName></X509SubjectName> <X509Certificate>MIIF8z</X509Certificate> </X509Data> </KeyInfo> </Signature> </tns:Header> <tns:Reply> <tns:Result>OK</tns:Result> <tns:ID idAuthority="" idType="" kind="" objectType=""/> <tns:operationId>0</tns:operationId> </tns:Reply> <tns:Payload> <tns:OperationSet> <tns:enforceMsgSequence>false</tns:enforceMsgSequence> </tns:OperationSet> <tns:Compressed>QlpoORdyRThQkAA=</tns:Compressed> </tns:Payload> </tns:ResponseMessage>
预期输出
{body:<tns:ResponseMessage xmlns:n1="urn:sap-com:document:sap:rfc:functions" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"><tns:Header><tns:Verb>reply</tns:Verb><tns:Noun>Compressed</tns:Noun><tns:User/><Signature xmlns=""><SignedInfo><CanonicalizationMethod Algorithm=""/><SignatureMethod Algorithm=""/></SignedInfo><SignatureValue>XW8UqTTcR==</SignatureValue><KeyInfo><X509Data><X509IssuerSerial><X509IssuerName></X509IssuerName><X509SerialNumber>1448033456</X509SerialNumber></X509IssuerSerial><X509SubjectName></X509SubjectName><X509Certificate>MIIF8z</X509Certificate></X509Data></KeyInfo></Signature></tns:Header><tns:Reply><tns:Result>OK</tns:Result><tns:ID idAuthority="" idType="" kind="" objectType=""/><tns:operationId>0</tns:operationId></tns:Reply><tns:Payload><tns:OperationSet><tns:enforceMsgSequence>false</tns:enforceMsgSequence></tns:OperationSet><tns:Compressed>QlpoORdyRThQkAA=</tns:Compressed></tns:Payload></tns:ResponseMessage>}
解决方案:DataWeave 2.0 转换脚本
%dw 2.0 output application/json var xmlAsString = write(payload, "application/xml", {indent: false}) var strippedXml = xmlAsString replace /\s+/ with "" --- { body: strippedXml }
脚本说明
- 序列化XML为无格式字符串:
write(payload, "application/xml", {indent: false})将输入的XML对象转为字符串,通过indent: false禁用自动格式化的缩进和换行。 - 清除所有空白字符:
xmlAsString replace /\s+/ with ""用正则匹配所有连续空白(空格、换行、制表符),替换为空字符串,彻底移除所有无关空白。 - 生成目标结构:将处理后的单行XML放入
body字段,输出符合要求的JSON结构。
特殊场景处理
如果XML文本节点中存在需要保留的空格(如<desc>hello world</desc>),需修改正则表达式,仅清除标签之间的空白:
var strippedXml = xmlAsString replace /(?<=>)\s+(?=<)/ with ""
内容的提问来源于stack exchange,提问作者Bianca Ilas
相关产品推荐
相关产品推荐

