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

如何使用Groovy XmlSlurper按标签属性提取XML中file节点的location值

问题排查与解决方案

1. 先修正XML语法错误

你提供的示例XML存在语法问题,<component name="B">下的file节点多写了一个双引号:

<!-- 错误写法 -->
<file location=""xyz/a/b/z.h" checksum="1558926677"/>
<!-- 修正后写法 -->
<file location="xyz/a/b/z.h" checksum="1558926677"/>

如果不修正该错误,XmlSlurper解析时会直接抛出格式异常,无法正常读取节点内容。

2. 修正GPath查询表达式

你原来的写法没有获取到预期结果,是因为没有使用Groovy的展开运算符处理多节点集合,且没有将GPath属性对象转为普通字符串,修正后的代码如下:

GPathResult xmlContent = new XmlSlurper().parse(config.genSourceRootDir.resolve('par.xml').toFile())
// 提取所有genFiles下file节点的location属性
List<String> generatedFiles = xmlContent.'**'.genFiles.file*.@location*.toString()

如果你需要更精确的匹配,避免其他层级的file节点被误匹配,可以用findAll过滤:

GPathResult xmlContent = new XmlSlurper().parse(config.genSourceRootDir.resolve('par.xml').toFile())
List<String> generatedFiles = xmlContent.'**'.findAll { node ->
    node.name() == 'file' && node.parent().name() == 'genFiles'
}*.@location*.toString()

说明

  • *.是Groovy的展开运算符,会对集合中的每一个元素执行后续操作,适配多个genFiles、多个file节点的遍历场景
  • 末尾的*.toString()用于将GPath属性对象转为普通Java字符串,避免后续使用时出现类型异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:57:01