Search code examples
xmlgroovyxmlslurper

How to remove attributes from XML node in groovy


I am trying to parse an XML file and get a subset of nodes, with certain attributes removed.

A sample of what I have tried:

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>

What I would like to get:

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

How can I remove "id" from the child node of "record" without extracting the child node?


Solution

  • You need:

    println new StreamingMarkupBuilder().bindNode(record) 
    

    Setting rec to the results of the each, sets it to record.foo, whereas I believe you want record