How I can find all elements in XML by their tag name in Groovy (GPath)?
I need to find all car
elements in this document:
<records>
<first>
<car>
<id>378932</id>
</car>
</first>
<second>
<foo>
<car>
<name>audi</name>
</car>
</foo>
</second>
</records>
This is what I tried and failed:
def xml = new XmlSlurper().parse(file)
assert xml.car.size() == 2
XML ParsingThe Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing.
XmlSlurper evaluates the structure lazily. So if you update the xml you'll have to evaluate the whole tree again. XmlSlurper returns GPathResult instances when parsing XML. XmlParser returns Node objects when parsing XML.
Groovy's internal XmlParser and XmlSlurper provide access to XML documents in a Groovy-friendly way that supports GPath expressions for working on the document. XmlParser provides an in-memory representation for in-place manipulation of nodes, whereas XmlSlurper is able to work in a more streamlike fashion.
GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().
This is how it works:
def xml = new XmlSlurper().parse(file)
def cars = xml.depthFirst().findAll { it.name() == 'car' }
assert cars.size() == 2
You can also do:
def xml = new XmlSlurper().parse(file)
def cars = xml.'**'.findAll { it.name() == 'car' }
Use an XMLSlurper
def records = new XmlSlurper().parseText(file)
records.depthFirst().findAll { !it.childNodes() && it.car}
/*Otherwise this returns the values for parent nodes as well*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With