遍历所有的Xpath结果(Iterate over all Xpath results)

2019-10-21 09:25发布

我有这样的代码:

#!/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")]' )

和,而不是返回所有节点(I提供//在XPath表达式),我只得到的第一个节点。 如何修改我的代码,以显示匹配的节点?

Answer 1:

根据文档http://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.html你通过evaluate你想要什么,默认为字符串。 所以要求NODESET:

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

并迭代产生的NodeList

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


文章来源: Iterate over all Xpath results