Ruby Can';使用Nokogiri从XML文档中检索Google命名空间中的数据
我有一个谷歌购物订阅源:Ruby Can';使用Nokogiri从XML文档中检索Google命名空间中的数据,ruby,xml,namespaces,nokogiri,google-shopping,Ruby,Xml,Namespaces,Nokogiri,Google Shopping,我有一个谷歌购物订阅源: <?xml version="1.0" encoding="utf-8" ?> <rss version="2.0" xmlns:g="http://base.google.com/ns/1.0"> <channel> <item> <title>test</title> <g:id>1</g:id> <g:color>blue<
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
<channel>
<item>
<title>test</title>
<g:id>1</g:id>
<g:color>blue</g:color>
</item>
<item>
<title>test2</title>
<g:id>2</g:id>
<g:color>red</g:color>
</item>
</channel></rss>
# attributes => ['title', 'g:id', 'g:color']
但这不会带来任何回报。我试过很多建议,但似乎都不管用。很明显,我错过了一些东西,但我不知道是什么
另一件我无法理解的事情是检索一个项目中所有属性的列表。因此,我的问题是如何从Google Shopping feed中检索以下数组:
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
<channel>
<item>
<title>test</title>
<g:id>1</g:id>
<g:color>blue</g:color>
</item>
<item>
<title>test2</title>
<g:id>2</g:id>
<g:color>red</g:color>
</item>
</channel></rss>
# attributes => ['title', 'g:id', 'g:color']
如果希望保留名称空间信息,最简单的解决方案可能是使用Xpath表达式 类似于
doc.xpath('//item').each_with_index do |node, i|
puts "Element #{i} attributes:"
node.xpath("*/text()").each do |element|
puts "#{element.name}: #{element.text}"
end
end
尝试在xpath中使用
和文本:
doc.css('channel > item').each do |item|
puts item.at_xpath('g:id').text
end
#=> 1
#=> 2
另一件我搞不懂的事情是检索所有
项目中的属性
您可以获得每个项的数组,如下所示:
doc.css('channel > item').map do |item|
item.element_children.map do |key|
prefix = "#{key.namespace.prefix}:" if key.namespace
name = key.name
"#{prefix}#{name}"
end
end
#=> [["title", "g:id", "g:color"], ["title", "g:id", "g:color"]]
如果所有项目都具有完全相同的属性,那么您可以只使用第一个元素(而不是迭代所有项目):
非常感谢你Gerry这正是我想要的!