迭代所有Xpath结果 [英] Iterate over all Xpath results

查看:162
本文介绍了迭代所有Xpath结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #!/ usr / bin / groovy 

import javax .xml.xpath。*
import javax.xml.parsers.DocumentBuilderFactory
$ b $ def testxml ='''
< Employee>
< ID> ..< / ID>
<电子邮件> ..< /电子邮件>
< custom_1> foo< / custom_1>
< custom_2>栏< / 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表达式中提供了 // ),我只获得第一个节点。如何修改我的代码以显示所有匹配的节点?

/docs.oracle.com/javase/7/docs/api/javax/xml/xpath/package-summary.htmlrel =nofollow> http://docs.oracle.com/javase/7/docs/api /javax/xml/xpath/package-summary.html 你传递 evaluate 你想要什么,默认为字符串。所以请求一个NODESET:

pre $ x $ c $ xpath.evaluate(xpathQuery,records,XPathConstants.NODESET)

并遍历结果的 NodeList

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


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 ?

解决方案

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
}

这篇关于迭代所有Xpath结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆