6

我有一个很大的 HTML 页面。但我想使用 Xpath 选择某些节点:

<html>
 ........
<!-- begin content -->
 <div>some text</div>
 <div><p>Some more elements</p></div>
<!-- end content -->
.......
</html>

我可以在使用后选择 HTML <!-- begin content -->

"//comment()[. = ' begin content ']/following::*" 

我也可以在使用之前选择 HTML <!-- end content -->

"//comment()[. = ' end content ']/preceding::*" 

但是我是否必须让 XPath 选择两条评论之间的所有 HTML?

4

1 回答 1

19

我会寻找在第一条评论之前和第二条评论之后的元素:

doc.xpath("//*[preceding::comment()[. = ' begin content ']]
              [following::comment()[. = ' end content ']]")
#=> <div>some text</div>
#=> <div>
#=>   <p>Some more elements</p>
#=> </div>
#=> <p>Some more elements</p>

请注意,上面为您提供了介于两者之间的每个元素。这意味着如果您遍历每个返回的节点,您将获得一些重复的嵌套节点 - 例如“更多元素”。

我认为您实际上可能只想获得介于两者之间的顶级节点 - 即评论的兄弟姐妹。这可以使用preceding/following-sibling代替来完成。

doc.xpath("//*[preceding-sibling::comment()[. = ' begin content ']]
              [following-sibling::comment()[. = ' end content ']]")
#=> <div>some text</div>
#=> <div>
#=>   <p>Some more elements</p>
#=> </div>

更新 - 包括评论

仅使用//*返回元素节点,其中不包括注释(和其他一些)。您可以更改*node()返回所有内容。

puts doc.xpath("//node()[preceding-sibling::comment()[. = 'begin content']]
                        [following-sibling::comment()[. = 'end content']]")
#=> 
#=> <!--keywords1: first_keyword-->
#=> 
#=> <div>html</div>
#=> 

如果您只想要元素节点和注释(即不是所有内容),您可以使用self轴:

doc.xpath("//node()[self::* or self::comment()]
                   [preceding-sibling::comment()[. = 'begin content']]
                   [following-sibling::comment()[. = 'end content']]")
#~ #=> <!--keywords1: first_keyword-->
#~ #=> <div>html</div>
于 2013-09-18T13:09:49.477 回答