2014-07-21 50 views
0

我有一个XML文档类似如下:引入nokogiri:忽略子节点

<doc> 
    <header> 
    <group> 
     <note>group note</note> 
    </group> 
    <note>header note</note> 
    </header> 
</doc> 

我希望检索标题下方落下的音符元素,而不是说下组落下任何音符元素。

我想这应该工作,但它也正在组拿起注:

doc.css('header note') 

什么是语法,只抢音符元素是标题的直接子?

+0

我认为第二个“”的标签被认为是关闭标签 - “”? –

回答

1

您可以使用CSS选择器的>寻子元素。这与使用找到后代元素的空间形成对照。

你的情况:

puts doc.css('header > note') 
#=> "<note>header note</note>" 
0

最简单的事情就是让引入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就像一个数组,因为您可以对其进行分片或使用firstlast

不过请注意,你可以很容易地使用:

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>]