Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
迭代所有Xpath结果_Xpath_Groovy_Xpathquery - Fatal编程技术网

迭代所有Xpath结果

迭代所有Xpath结果,xpath,groovy,xpathquery,Xpath,Groovy,Xpathquery,我有以下代码: #!/usr/bin/groovy import javax.xml.xpath.* import javax.xml.parsers.DocumentBuilderFactory def testxml = ''' <Employee> <ID>..</ID> <E-mail>..</E-mail>

我有以下代码:

#!/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")]' )
#/usr/bin/groovy
导入javax.xml.xpath*
导入javax.xml.parsers.DocumentBuilderFactory
def testxml=''
..
..
福
酒吧
基础
'''
def processXml(字符串xml、字符串xpathQuery){
def xpath=XPathFactory.newInstance().newXPath()
def builder=DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream=new ByteArrayInputStream(xml.bytes)
def records=builder.parse(inputStream.documentElement)
evaluate(xpathQuery,记录)
}
println processXml(testxml,'/*[以(name(),“custom”)]开头])
而不是返回所有节点(我在Xpath表达式中提供了
/
),我只得到第一个节点。如何修改代码以显示所有匹配的节点?

根据您传递的文档评估所需内容,默认为字符串。因此,请求节点集:

xpath.evaluate( xpathQuery, records, XPathConstants.NODESET )
并迭代生成的
节点列表

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

谢谢,如果你能把整个过程缩短,我很感兴趣;)