注释之间的XPath选择多次(XPath selecting between comments mu

2019-10-21 03:21发布

我们需要阅读HTML注释之间的节点:

<html>
<!-- comment 1 -->
 <div>some text</div>
 <div><p>Some more elements</p></div>
<!-- end content -->

<!-- comment 2 -->
 <div>some text</div>
 <div><p>Some more elements</p>
 <!-- end content -->
 </div>
</html>

我试着用下面的XPath:

//*[preceding-sibling::comment()[contains(., 'comment 1')]][following-sibling::comment()[contains(., 'end content')]]

它工作正常的第一个评论即评论1,但不工作的第二个评论下面是相同的的XPath

//*[preceding-sibling::comment()[contains(., 'comment 2')]][following-sibling::comment()[contains(., 'end content')]]

我使用的HTML敏捷性包与下面的代码:

var nodes = document.SelectNodes("//*[preceding-sibling::comment()[contains(., 'comment 1')]][following-sibling::comment()[contains(., 'InstanceEndEditable')]]");

string allHtml = nodes[0].OuterHtml;

如果我改变“注释1”在上面的代码“注释2”,那么它是不会放弃任何结果。

Answer 1:

添加,指出你想第1跟前评论和第一其后的评论断言。

因此,举例来说,要获得与“注释1”开头的注释的内容:

//*[preceding-sibling::comment()[1][contains(., 'comment 1')]]
   [following-sibling::comment()[1][contains(., 'end content')]]

同样,要获得与“注释2”开头的注释的内容:

//*[preceding-sibling::comment()[1][contains(., 'comment 2')]]
   [following-sibling::comment()[1][contains(., 'end content')]]


文章来源: XPath selecting between comments multiple times