如何从 groovy 中的 XML 节点删除属性

How to remove attributes from XML node in groovy

我正在尝试解析 XML 文件并获取节点子集,其中删除了某些属性。

我尝试过的示例:

def xml = """<root>
  <record class="test">Some text
   <foo  id="something">Foo</foo>
  </record>
  <record>Some other text</record>
  </root>"""

   def root = new XmlSlurper().parseText(xml)
   def record = root.record.find{ it.@class=='test'}
   println new StreamingMarkupBuilder().bindNode(record)

// Output:
// <record class='test'>Some text
// <foo id='something'>Foo</foo></record>

   def rec = record.foo.each { p -> p.attributes().remove('id') }
   println rec
   println new StreamingMarkupBuilder().bindNode(rec)

// Output:
// <foo>Foo</foo>

我想得到什么:

// <record class='test'>Some text
//  <foo>Foo</foo></record>

如何在不提取子节点的情况下从"record"的子节点中删除"id"?

你需要:

println new StreamingMarkupBuilder().bindNode(record) 

rec 设置为 each 的结果,将其设置为 record.foo,而我相信您想要记录