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