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