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

如何用Groovy提取XML中的ID值?现有脚本输出异常求指导

Groovy提取XML中CustomerQuote节点下ID值的问题修正

原脚本问题分析

  1. 根节点访问错误:XmlSlurper.parseText(xml)返回的是XML的根节点<Collection>,因此completeXml已经代表该根节点,后续无需再通过completeXml.Collection访问,这会导致找不到目标节点。
  2. 过滤条件逻辑错误:findAll{node-> node.name() == 'ID' }中的node是CustomerQuote节点,其节点名称是CustomerQuote而非ID,因此永远匹配不到目标内容,最终返回空数组。

修正后的脚本

写法一(简洁版)

直接遍历所有CustomerQuote节点,提取每个节点下ID的文本值:

def xml="&lt;Collection&gt;&lt;CustomerQuote&gt;&lt;ID&gt;99988877766&lt;/ID&gt;&lt;TypeCode&gt;2059&lt;/TypeCode&gt;&lt;ApprovalStatusCode&gt;4&lt;/ApprovalStatusCode&gt;&lt;/CustomerQuote&gt;&lt;CustomerQuote&gt;&lt;ID&gt;99988877755&lt;/ID&gt;&lt;TypeCode&gt;2059&lt;/TypeCode&gt;&lt;ApprovalStatusCode&gt;4&lt;/ApprovalStatusCode&gt;&lt;/CustomerQuote&gt;&lt;/Collection&gt;"

def completeXml = new XmlSlurper().parseText(xml);
def IDs = completeXml.CustomerQuote.ID*.text();
// 输出:IDs[99988877766, 99988877755]

写法二(显式遍历)

使用collect方法显式处理每个CustomerQuote节点:

def xml="&lt;Collection&gt;&lt;CustomerQuote&gt;&lt;ID&gt;99988877766&lt;/ID&gt;&lt;TypeCode&gt;2059&lt;/TypeCode&gt;&lt;ApprovalStatusCode&gt;4&lt;/ApprovalStatusCode&gt;&lt;/CustomerQuote&gt;&lt;CustomerQuote&gt;&lt;ID&gt;99988877755&lt;/ID&gt;&lt;TypeCode&gt;2059&lt;/TypeCode&gt;&lt;ApprovalStatusCode&gt;4&lt;/ApprovalStatusCode&gt;&lt;/CustomerQuote&gt;&lt;/Collection&gt;"

def completeXml = new XmlSlurper().parseText(xml);
def IDs = completeXml.CustomerQuote.collect { customerQuote ->
    customerQuote.ID.text()
}
// 输出:IDs[99988877766, 99988877755]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:37:14