How do I create an XPath function in Groovy

You can do something like this:

import javax.xml.xpath.*
import javax.xml.parsers.DocumentBuilderFactory

def testxml=""'
    <records>
      <car name="HSV Maloo" make="Holden" year="2006">
        <country>Australia</country>
        <record type="speed">Production Pickup Truck with speed of 271kph</record>
      </car>
    </records>
  '''

def processXml( String xml, String xpathQuery ) {
  def xpath = XPathFactory.newInstance().newXPath()
  def builder     = DocumentBuilderFactory.newInstance().newDocumentBuilder()
  def inputStream = new ByteArrayInputStream( xml.bytes )
  def records     = builder.parse(inputStream).documentElement
  xpath.evaluate( xpathQuery, records )
}

println processXml( testxml, '//car/record/@type' )

Have a look at this page (formerly part of the Groovy Docs) for how to loop over XPath queries that will return multiple results:

http://groovy.jmiguel.eu/groovy.codehaus.org/Reading+XML+with+Groovy+and+XPath.html

Leave a Comment