Iterate over all Xpath results

1.5k views Asked by At

I have this code:

#!/usr/bin/groovy

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

def testxml = '''
                <Employee>
                  <ID>..</ID>
                  <E-mail>..</E-mail>
                  <custom_1>foo</custom_1>
                  <custom_2>bar</custom_2>
                  <custom_3>base</custom_3>
                </Employee>
  '''

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, '//*[starts-with(name(), "custom")]' )

and instead of returning all the nodes (I provided // in Xpath expression), I get only the first node. How can I modify my code to display all the matching nodes ?

1

There are 1 answers

1
cfrick On BEST ANSWER

according to the docs http://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.html you pass evaluate what you want, which defaults to string. So request a NODESET:

xpath.evaluate( xpathQuery, records, XPathConstants.NODESET )

and iterate over the resulting NodeList:

def result = processXml( testxml, '//*[starts-with(name(), "custom")]' )
result.length.times{
        println result.item(it).textContent
}