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

Groovy脚本:如何按要求拼接XML列表元素为竖线分隔字符串

XML Value值提取与带空值的拼接处理

需求描述

从给定XML中提取所有Value节点的内容,每个元素(包括无Value节点的空值)后添加|,每个InputDataList对应一行拼接后的字符串。

原始XML内容

<n0:SendData xmlns:n0="http://testdata/"
             xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    <Operation>Testing1</Operation>
    <InputDataList>
        <InputData>
            <Field>ATTRIBUTE1</Field>
            <Value>1.000</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE2</Field>
            <Value>test</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE3</Field>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE4</Field>
            <Value>testend</Value>
        </InputData>
    </InputDataList>
    <InputDataList>
        <InputData>
            <Field>ATTRIBUTE1</Field>
            <Value>2.000</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE2</Field>
            <Value>test2</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE3</Field>
            <Value>test2end</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE4</Field>
        </InputData>
    </InputDataList>
</n0:SendData>

现有Groovy代码

def xml = new XmlSlurper().parseText(data)

def items = xml.InputDataList.each { node ->
    node.InputData.Field.text() == ""
}.collect { node ->
    node.InputData.with {
        "${InputData.text()}|
"
    }
}

println items

当前输出

1.000testtestend|
2.000test2testend2|

预期输出

1.000|test||testend
2.000|test2|test2end||

问题分析与修正代码

原代码的问题在于直接调用InputData.text()会将所有子节点的文本直接拼接,且未处理无Value节点的空值场景。修正后的代码需要逐个处理每个InputData节点,提取Value内容(空值用空字符串替代),再用|连接:

def xml = new XmlSlurper().parseText(data)

def items = xml.InputDataList.collect { listNode ->
    // 遍历每个InputData,提取Value文本,无则为空字符串
    listNode.InputData.collect { dataNode ->
        dataNode.Value.text() ?: ''
    }.join('|') // 用|连接所有元素,自动包含空值位置的分隔符
}

// 输出结果
items.each { println it }

代码说明

  1. 遍历每个InputDataList节点,作为单独的行处理
  2. 对每个InputData节点,提取Value的文本内容;若Value节点不存在,使用空字符串替代
  3. 通过join('|')将所有元素(包括空值)用|连接,正好满足每个元素后带|的格式要求,同时保留空值位置的分隔符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:02:38