1

我有这个代码:

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

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

4

1 回答 1

2

根据文档http://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.html你传递evaluate你想要的,默认为字符串。所以请求一个节点集:

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

并遍历结果NodeList

def result = processXml( testxml, '//*[starts-with(name(), "custom")]' )
result.length.times{
        println result.item(it).textContent
}
于 2014-12-10T18:10:25.540 回答