You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用DataWeave 2.0移除XML中[@...]格式的内容?

移除XML中特定格式子串的正确DataWeave实现

问题背景

需要移除XML里所有以[@开头、]结尾的子串(包含首尾内容),之前直接把XML转成字符串用replace处理,不仅没彻底清掉目标内容,还搞坏了XML结构,导致differences标签下的内容变成null。

输入XML示例

<root>
  <element>abc[@attr='123']def</element>
  <differences>
    <item>xyz[@id='456']uvw</item>
  </differences>
</root>

期望输出XML示例

<root>
  <element>abcdef</element>
  <differences>
    <item>xyzuvw</item>
  </differences>
</root>

错误尝试的DataWeave代码

%dw 2.0
output application/xml
---
payload as String replace /\[@.*?\]/ with "" as Object

正确实现方案

直接把整个XML转字符串处理会破坏节点结构,导致解析异常。正确思路是遍历XML的文本节点单独处理,保留原有XML结构。

通用递归处理方案(适配任意XML结构)

%dw 2.0
output application/xml

fun cleanText(node) = 
    node match {
        case is String -> node replace /\[@.*?\]/ with ""
        case is Object -> node mapObject (value, key) -> 
            { (key): cleanText(value) }
        case is Array -> node map cleanText($)
        else -> node
    }
---
cleanText(payload)

定向节点处理方案(已知目标节点路径时用)

如果明确知道要处理哪些节点,用update更高效:

%dw 2.0
output application/xml
---
payload update [
    "element": $ replace /\[@.*?\]/ with "",
    "differences.*": $ replace /\[@.*?\]/ with ""
]

方案说明

  • 递归方案会遍历所有节点,只对文本内容做正则替换,完全保留XML的节点层级和结构,不会出现null问题。
  • 定向方案针对指定节点处理,性能更优,适合结构固定的场景。
  • 正则用.*?非贪婪匹配,确保只移除单个[@... ]子串,不会误删多个目标子串之间的内容。

内容的提问来源于stack exchange,提问作者Zak01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:52:08