使用Groovy脚本基于字段值过滤XML中CompoundEmployee节点问题求助
Groovy 过滤XML节点解决方案
原脚本存在的问题
- 筛选出的合法
CompoundEmployee节点没有挂载回原XML根节点,直接序列化节点数组会丢失完整XML结构 - 校验逻辑可通过Groovy内置集合方法简化,无需手动维护flag变量
修正后完整可运行代码
import groovy.xml.* // 替换为实际的XML内容 def body = """ <?xml version="1.0" encoding="UTF-8"?> <queryCompoundEmployeeResponse> <CompoundEmployee> <id>970</id> <person> <birth_name>Name1</birth_name> <employment_information> <job_information> <custom_string13>MD_6_DAY</custom_string13> <custom_string14>MW_9X</custom_string14> </job_information> <job_information> <custom_string13>MD_6_DAY</custom_string13> <custom_string14>MW_9S</custom_string14> </job_information> </employment_information> </person> </CompoundEmployee> <CompoundEmployee> <id>130</id> <person> <birth_name>Name2</birth_name> <employment_information> <job_information> <custom_string13>MD_6_DAY</custom_string13> <custom_string14>MW_9R</custom_string14> </job_information> <job_information> <custom_string13>MD_6_DAY</custom_string13> <custom_string14>MW_9R</custom_string14> </job_information> </employment_information> </person> </CompoundEmployee> </queryCompoundEmployeeResponse> """ def allowedValues = ["MW_9X", "MW_9R"] def root = new XmlParser().parseText(body) // 过滤规则:仅保留所有custom_string14值都在允许列表内的CompoundEmployee def validEmployees = root.CompoundEmployee.findAll { employee -> employee.'**'.custom_string14.every { cs14 -> allowedValues.contains(cs14.text().trim()) } } // 替换根节点下的子节点为筛选后的合法节点 root.remove(root.CompoundEmployee) validEmployees.each { root.append(it) } // 输出格式化后的XML def outputXml = XmlUtil.serialize(root) println outputXml
输出效果
针对示例XML,运行后仅会保留id为130的CompoundEmployee节点,id为970的节点因存在custom_string14=MW_9S的非法值被过滤,输出的XML结构和原格式完全一致。
内容的提问来源于stack exchange,提问作者Nitin
相关产品推荐
相关产品推荐

