我有一个很大的 HTML 页面。但我想使用 Xpath 选择某些节点:
<html>
........
<!-- begin content -->
<div>some text</div>
<div><p>Some more elements</p></div>
<!-- end content -->
.......
</html>
我可以在之后选择 HTML<!-- begin content -->
using:
"//comment()[. = ' begin content ']/following::*"
我也可以在之前选择 HTML<!-- end content -->
using:
"//comment()[. = ' end content ']/preceding::*"
但是我是否必须使用 XPath 来选择两条注释之间的所有 HTML?
我会查找第一个注释前面和第二个注释后面的元素:
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>
请注意,上面为您提供了each之间的元素。这意味着,如果您迭代每个返回的节点,您将得到一些重复的嵌套节点 - 例如“更多元素”。
我认为您实际上可能只想获取中间的顶级节点 - 即注释的兄弟节点。这可以使用以下方法完成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>
更新 - 包括评论
Using //*
仅返回元素节点,不包括注释(和其他一些)。你可以改变*
to node()
归还一切。
puts doc.xpath("//node()[preceding-sibling::comment()[. = 'begin content']]
[following-sibling::comment()[. = 'end content']]")
#=>
#=> <!--keywords1: first_keyword-->
#=>
#=> <div>html</div>
#=>
如果您只想要元素节点和注释(即不是所有内容),您可以使用self
axis:
doc.xpath("//node()[self::* or self::comment()]
[preceding-sibling::comment()[. = 'begin content']]
[following-sibling::comment()[. = 'end content']]")
#~ #=> <!--keywords1: first_keyword-->
#~ #=> <div>html</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)