如何打印XPath搜索?

时间:2016-06-20 20:30:02

标签: ruby xpath nokogiri

我试图用Nokogiri解析XML文件:

 require 'nokogiri'
 require 'open-uri'

  @doc = Nokogiri::XML(open('http://xml.pinnaclesports.com/pinnacleFeed.aspx?sportType=E%20Sports&contest=no'))
  @doc.xpath("//event[@league='*LOL*']")
  print @doc.text

工作并打印包含" LOL"的所有事件。在"联盟"属性,但是当我创建一个块时,它会运行但不打印任何内容:

@doc.xpath("//event[@league='*LOL*']").each do |league_element|
   puts "\n"+league_element.xpath('league').text
end

1 个答案:

答案 0 :(得分:0)

require 'nokogiri'
require 'open-uri'

@doc = Nokogiri::XML(open('http://xml.pinnaclesports.com/pinnacleFeed.aspx?sportType=E%20Sports&contest=no'))
events = @doc.xpath("//event[@league='*LOL*']")
puts @doc.children

.children"返回一个新NodeSet,其中包含NodeSet中所有节点的所有子节点。"您可以使用children.xpath()

继续过滤节点名称和值

例如:

@doc = Nokogiri::XML(open('http://xml.pinnaclesports.com/pinnacleFeed.aspx?sportType=E%20Sports&contest=no'))
events = @doc.xpath("//event[@league='*LOL*']")
puts @doc.children.xpath('//league').text

=> LOL Cham Kor
=> LOL Cham Kor
=> ....

或者

@doc.children.each do |item|
  puts item.xpath('//league')
end