Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all XML elements by tag name in Groovy?

Tags:

xml

groovy

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
like image 649
yegor256 Avatar asked Jul 17 '11 20:07

yegor256


People also ask

How do I read XML content in groovy?

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.

Why do we use XML Surpler in groovy?

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.

What is groovy XmlSlurper?

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.

What is GPathResult?

GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text().


3 Answers

This is how it works:

def xml = new XmlSlurper().parse(file)
def cars = xml.depthFirst().findAll { it.name() == 'car' }
assert cars.size() == 2
like image 133
yegor256 Avatar answered Oct 21 '22 13:10

yegor256


You can also do:

def xml = new XmlSlurper().parse(file)
def cars = xml.'**'.findAll { it.name() == 'car' }
like image 39
tim_yates Avatar answered Oct 21 '22 15:10

tim_yates


Use an XMLSlurper

def records = new XmlSlurper().parseText(file)
reco​rds.depthFirst()​.findAll { !it.childNodes() && it.car} ​

/*Otherwise this returns the values for parent nodes as well*/
like image 45
Igor Avatar answered Oct 21 '22 13:10

Igor