XPath在多次评论之间进行选择 [英] XPath selecting between comments multiple times

查看:104
本文介绍了XPath在多次评论之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < html> 
<! - comment 1 - >
< div>一些文字< / div>
< div>< p>更多元素< / p>< / div>
<! - 结束内容 - >

<! - comment 2 - >
< div>一些文字< / div>
< div>< p>更多元素< / p>
<! - 结束内容 - >
< / div>
< / html>

我尝试使用下面的XPath:



<$ (包括(。,'comment 1')]] [following-sibling :: comment()[contains(。,'end内容')]]

它对第一条评论正常,即评论1,但不适用于第二条评论
以下是相同的XPath。

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

我使用以下代码的HTML Agility Pack:

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

string allHtml =节点[0] .OuterHtml;

如果我在上面的代码中将comment 1更改为comment 2,那么它不会给出任何结果。

解决方案

添加一个谓词,表明您希望先前的注释 第一个下面的评论。

所以,例如,要获取以comment 1开头的评论之间的内容, :

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

同样,要获得以comment 2开头的评论之间的内容:

  // * [before-sibling :: comment()[1] [contains(。,'comment 2')]] 
[following-sibling :: comment()[1] [contains(。,'end内容')]]


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.

解决方案

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')]]

这篇关于XPath在多次评论之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆