Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xpath 查找注释()的位置索引_Xpath - Fatal编程技术网

Xpath 查找注释()的位置索引

Xpath 查找注释()的位置索引,xpath,Xpath,面对这一点: <div> some text <!-- this is the hook comment--> target part 1 target part 2 <!-- this is another comment--> some other text </div> 或者使用前面的同级::*,不返回任何内容 所以我决定试试别的。xml的计数(//node())返回6。和//node()[2]返回相关的注释()。但是当我试图通过使用in

面对这一点:

<div>
some text
<!-- this is the hook comment-->
target part 1
target part 2
<!-- this is another comment-->
some other text
</div> 
或者使用前面的同级::*,不返回任何内容

所以我决定试试别的。xml的
计数(//node())
返回
6
。和
//node()[2]
返回相关的
注释()。但是当我试图通过使用
index-of()
(应该返回
2
)来获取该注释的位置时

它返回
3


当然,我可以忽略这一点,使用
3
索引位置作为目标文本的位置(而不是将
2
增加1),但我想知道,首先,结果是什么,其次,它是否有任何意外的后果。

没有必要首先找到
位置()如果要获取两条注释之间的节点,请使用元素的
(仅供参考
position()
取决于您选择的整个节点集)

您可以直接获取元素-这里是
text()
节点。所以像这样的示例文件

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <div>
    some text
    <!-- this is the hook comment-->
    target part 1
    target part 2
    <!-- this is another comment-->
    some other text
        <!-- this is another comment-->
    no one needs this
        <!-- this is another comment-->
    this is also useless
        <!-- this is another hook comment-->
    second target text
        <!-- this is another comment-->
    again some useless crap
        <!-- this is another comment-->
    and the last piece that noone needs
    </div> 
</root>
导致

target part 1
target part 2

second target text
如果只需要第一个块,请将表达式限制为第一项:

(//comment()[contains(string(),'hook')]/following-sibling::text()[preceding-sibling::comment()[1][contains(string(),'hook')]])[1]
其结果是

target part 1
target part 2
如所愿



如果可以使用XPath-2.0,则可以在上面的表达式中附加一个
/position()
,以获取
注释()
的位置。但是,如上所述,它们是相对于注释节点的。因此,结果将是
12

这些表达式会让你头晕目眩,但肯定有用!谢谢
target part 1
target part 2

second target text
(//comment()[contains(string(),'hook')]/following-sibling::text()[preceding-sibling::comment()[1][contains(string(),'hook')]])[1]
target part 1
target part 2