Reputation: 1620
I have the following sample XML: http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=visitors,countries,searches (dummy xml data)
I want to specify the node "countries", then search through all of the "items" and extract various data. I'm attempting to do this with:
xml = Nokogiri::XML(open("http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=visitors,countries,searches"))
@node = xml.xpath('//countries')
@countries = @node.search('item').map do |item|
%w[title value value_percent].each_with_object({}) do |n, o|
o[n] = item.at(n).text
end
end
end
But this doesn't give any results. If I strip the xml back to http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=visitors and do:
xml = Nokogiri::XML(open("http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=countries"))
@countries = @node.search('item').map do |item|
%w[title value value_percent].each_with_object({}) do |n, o|
o[n] = item.at(n).text
end
end
end
This works fine.
Where am I going wrong here?
Upvotes: 1
Views: 815
Reputation: 5019
You xpath-query will only match nodes with name "countries" and not nodes that has the type-attribute set to "countries". So you will need to search for nodes that has a attribute "type" with value set to "countries"
Three ways for finding all items for countries
# (1) Find all nodes with a attribute "type" set to "countries"
items = xml.xpath("//*[@type='countries']//item")
# (2) Find only nodes with name "type" and that has the attribute "type" set to "countries"
items = xml.xpath("//type[@type='countries']//item")
# (3) By using css selectors; find only nodes with name "type" and that has the attribute "type" set to "countries"
items = xml.css("type[type='countries'] item")
Upvotes: 3