任何人都知道如何使用xpath获取节点的位置?
说我有以下xml:
<a>
<b>zyx</b>
<b>wvu</b>
<b>tsr</b>
<b>qpo</b>
</a>
Run Code Online (Sandbox Code Playgroud)
我可以使用以下xpath查询来选择第三个<b>节点(<b> tsr </ b>):
a/b[.='tsr']
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但我想返回该节点的序号位置,如:
a/b[.='tsr']/position()
Run Code Online (Sandbox Code Playgroud)
(但更多工作!)
它甚至可能吗?
编辑:忘了提到我正在使用.net 2所以它是xpath 1.0!
更新:结束使用James Sulak的出色答案.对于那些感兴趣的人,我在C#中的实现:
int position = doc.SelectNodes("a/b[.='tsr']/preceding-sibling::b").Count + 1;
// Check the node actually exists
if (position > 1 || doc.SelectSingleNode("a/b[.='tsr']") != null)
{
Console.WriteLine("Found at position = {0}", position);
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*lak 92
尝试:
count(a/b[.='tsr']/preceding-sibling::*)+1.
Run Code Online (Sandbox Code Playgroud)
您可以使用XSLT执行此操作,但我不确定直接XPath.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"
omit-xml-declaration="yes"/>
<xsl:template match="a/*[text()='tsr']">
<xsl:number value-of="position()"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
小智 7
我意识到这个帖子很古老..但..
用节点代替星号可以给你更好的结果
count(a/b[.='tsr']/preceding::a)+1.
Run Code Online (Sandbox Code Playgroud)
代替
count(a/b[.='tsr']/preceding::*)+1.
Run Code Online (Sandbox Code Playgroud)
如果您升级到 XPath 2.0,请注意它提供了函数index-of,它以这种方式解决问题:
index-of(//b, //b[.='tsr'])
Run Code Online (Sandbox Code Playgroud)
在哪里: