XPath selecting between comments multiple times

孤人 提交于 2019-12-11 11:35:44

问题


We need to read node between HTML comments:

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

I tried using the below XPath:

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

It works fine for first comment i.e. comment 1 but not working for second comment following is the XPath for the same

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

I am using HTML Agility Pack with below code:

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

string allHtml = nodes[0].OuterHtml;

If I change "comment 1" to "comment 2" in above code then it is not giving any result.


回答1:


Add a predicate that states that you want the first preceding comment and the first following comment.

So, for example, to get the contents between the comments that starts with "comment 1":

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

Similarly, to get the contents between the comments that starts with "comment 2":

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


来源:https://stackoverflow.com/questions/26404345/xpath-selecting-between-comments-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!