我会寻找在第一条评论之前和第二条评论之后的元素:
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>