【问题标题】:Iterate over all Xpath results遍历所有 Xpath 结果
【发布时间】:2015-02-09 01:10:39
【问题描述】:

我有这个代码:

#!/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 表达式中提供了//),我只得到第一个节点。如何修改我的代码以显示所有匹配的节点?

【问题讨论】:

    标签: xpath groovy xpathquery


    【解决方案1】:

    根据文档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
    }
    

    【讨论】:

    • 谢谢,如果你能做得更短,我很感兴趣;)
    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多