Michael Cutrone Michael Cutrone - 5 months ago 27
Ruby Question

How to print XPath search?

I'm trying to parse an XML file with Nokogiri:

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


which works and prints all the events that contain "LOL" in the "league" attribute, but when I create a block, it runs but prints nothing:

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

Answer
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 "returns a new NodeSet containing all the children of all the nodes in the NodeSet." you can keep filtering node names and values using children.xpath()

For example:

@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
=> ....

Or

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