Nokogiri 的 CSS 和 XPath 访问器都允许指定多个标签,这对于这类问题很有用。而不是遍历文档的page 标签中的每个标签:
require 'nokogiri'
doc = Nokogiri::XML('
<xml>
<body>
<image>image</image>
<text>text</text>
<video>video</video>
<other>other</other>
<image>image</image>
<text>text</text>
<video>video</video>
<other>other</other>
</body>
</xml>')
这是使用 CSS 进行的搜索:
doc.search('image, text, video').each do |node|
case node.name
when 'image'
puts node.text
when 'text'
puts node.text
when 'video'
puts node.text
else
puts 'should never get here'
end
end
# >> image
# >> image
# >> text
# >> text
# >> video
# >> video
请注意,它按照 CSS 访问器指定的顺序返回标签。如果需要文档中标签的顺序,可以使用XPath:
doc.search('//image | //text | //video').each do |node|
puts node.text
end
# >> image
# >> text
# >> video
# >> image
# >> text
# >> video
在任何一种情况下,程序都应该运行得更快,因为所有搜索都发生在 libXML 中,只返回 Ruby 处理所需的节点。
如果您需要将搜索限制在 <page> 标记内,您可以预先搜索以找到 page 节点,然后在其下方搜索:
doc.at('page').search('image, text, video').each do |node|
...
end
或
doc.at('//page').search('//image | //text | //video').each do |node|
...
end