我有以下示例XML: http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=visitors,countries,searches(虚拟XML数据)
我想指定节点"countries",然后搜索所有"items"并提取各种数据。我正在尝试这样做:
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
但是这没有给出任何结果。如果我将xml剥离回http://api.clicky.com/api/stats/4?site_id=32020&sitekey=71bf7c1681e22468&type=visitors并执行:
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
这很好。
我哪里错了?
xpath-query将只匹配名称为" nations "的节点,而不匹配类型属性设置为" nations "的节点。因此,您需要搜索具有属性"type"且值设置为"nations"的节点
查找国家/地区所有项目的三种方法
# (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")