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

如何修改DataWeave 1.0函数实现XML匹配键的标签/属性/值移除

扩展DataWeave 1.0函数实现XML全维度字段过滤

现有DataWeave 1.0函数只能移除XML中的指定标签名,现在需要扩展逻辑,让它同时处理属性名和值——只要字段名或值匹配过滤列表,就把对应的标签、属性或值移除。

原代码局限

原函数只检查并移除匹配的标签名,完全没处理属性和值的过滤:

%dw 1.0
%output application/xml skipNullOn="everywhere"
%function remove(content, filterList)
    content match {
        :array -> $ map (value,index) -> remove(value, filterList),
        :object -> $ mapObject (value,key) ->
            (key) @((key.@)) : null when (filterList contains key as :string)
                otherwise remove(value, filterList)
            ,
        default -> content
    }
---
remove(payload, ["userId","companyId","account"])

修改后的完整代码

下面的代码扩展了过滤逻辑,覆盖标签、属性、值三个维度:

%dw 1.0
%output application/xml skipNullOn="everywhere"
%function remove(content, filterList)
    content match {
        // 递归处理数组内的每个元素
        :array -> $ map (value, index) -> remove(value, filterList),
        // 处理XML标签(对象类型)
        :object -> $ mapObject (value, key) -> 
            // 先过滤属性:移除属性名在过滤列表中的项
            (key) @(key.@ filterObject ((attrVal, attrKey) -> !(filterList contains attrKey as :string))) : 
                // 处理值:如果是字符串且匹配过滤列表,返回null移除
                null when (filterList contains value as :string)
                otherwise remove(value, filterList)
            // 如果标签名在过滤列表里,直接移除整个标签
            when (filterList contains key as :string)
            otherwise (
                (key) @(key.@ filterObject ((attrVal, attrKey) -> !(filterList contains attrKey as :string))) : 
                    null when (filterList contains value as :string)
                    otherwise remove(value, filterList)
            ),
        // 单独处理字符串值:匹配则移除
        :string -> null when (filterList contains content) otherwise content,
        // 其他类型(数字、布尔等)直接保留
        default -> content
    }
---
remove(payload, ["userId","companyId","account"])

代码逻辑说明

  • 数组处理:和原逻辑一致,递归遍历数组每个元素,确保嵌套数组也能被处理
  • 标签属性过滤:用filterObject遍历标签的所有属性,只保留属性名不在过滤列表里的项
  • 标签名过滤:如果标签名匹配过滤列表,直接返回null(结合skipNullOn="everywhere"会自动移除该标签)
  • 值过滤:如果标签值是字符串且匹配过滤列表,返回null移除该值;非字符串值或不匹配的则递归处理
  • 字符串值单独处理:避免嵌套对象里的字符串值被遗漏,单独判断后决定是否移除

示例效果

输入XML:

<root>
    <userId>12345</userId>
    <userInfo userName="test" account="admin">
        <companyId>67890</companyId>
        <email>test@example.com</email>
        <role>account</role>
    </userInfo>
</root>

处理后输出:

<root>
    <userInfo userName="test">
        <email>test@example.com</email>
    </userInfo>
</root>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:25:07