最简单的事情就是让引入nokogiri找到所有header note
标签,则只能使用最后一个:
require 'nokogiri'
doc = Nokogiri::XML(<<EOT)
<doc>
<header>
<group>
<note>group note</note>
<group>
<note>header note</note>
</header>
</doc>
EOT
doc.css('header note').last.text # => "header note"
记住,css
,像它的XPath对口xpath
,以及更通用search
,返回节点集。 NodeSets就像一个数组,因为您可以对其进行分片或使用first
或last
。
不过请注意,你可以很容易地使用:
doc.css('note').last.text # => "header note"
公告虽然,你的XML格式不正确。 <group>
标记未关闭。 Nokogiri正在对XML进行修复,这可能会给你一些奇怪的结果。检查这种情况通过查看doc.errors
:
# => [#<Nokogiri::XML::SyntaxError: Opening and ending tag mismatch: group line 5 and header>,
# #<Nokogiri::XML::SyntaxError: Opening and ending tag mismatch: group line 3 and doc>,
# #<Nokogiri::XML::SyntaxError: Premature end of data in tag header line 2>,
# #<Nokogiri::XML::SyntaxError: Premature end of data in tag doc line 1>]
我认为第二个“”的标签被认为是关闭标签 - “ ”? –