Dmitry E. Dmitry E. - 6 months ago 65
Groovy Question

Remove all children from a Groovy xml node

So I have what would seem like a very common and simple task: given a Groovy Node (from XmlParser), I want to remove all its children.

Turns out it's not that simple. Most of the ways that I could think of resulted in a ConcurrentModificationException. Even using an iterator didn't help, which was surprising to me.

The only way I managed to do it was by first copying all children into a new list, then iterating that list. Something like this:

def children = []
children.addAll( node.children() )
children.each { node.remove(it) }

Isn't there a better, groovier way to do it?


Could be too simplistic, but I think you can just set the node's value to empty string.

import groovy.xml.*

def xml = "<parent><child>Child</child><another>One</another></parent>"

def node = new XmlParser().parseText(xml)

node.value = ""

println XmlUtil.serialize(node)