index-of()函数用于查找值在序列中首次出现的位置,从1开始计数,未找到则返回空序列,该函数属于XPath 2.0及以上版本,XPath 1.0需通过count和preceding-sibling等方法模拟实现,且处理节点等复杂类型时需转换为字符串比较。

XPath的
index-of()
解决方案:
index-of()
index-of(sequence, value)
sequence
value
例如,假设我们有以下XML文档:
<books>
<book>
<title>The Lord of the Rings</title>
<author>J.R.R. Tolkien</author>
</book>
<book>
<title>The Hobbit</title>
<author>J.R.R. Tolkien</author>
</book>
<book>
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
</books>要查找作者 "J.R.R. Tolkien" 在所有
author
index-of(/books/book/author, "J.R.R. Tolkien")
这个表达式会返回
1
author
再比如,如果我们要查找书名 "The Hobbit" 在所有
title
index-of(/books/book/title, "The Hobbit")
这个表达式会返回
2
如果我们要查找一个不存在的值,比如 "George Orwell",那么表达式:
index-of(/books/book/author, "George Orwell")
会返回一个空序列,在XPath 1.0中,这通常会被转换为空字符串或
NaN
需要注意的是:
index-of()
index-of()
index-of()
XPath 1.0没有内置的
index-of()
例如,可以使用以下XPath表达式来查找作者 "J.R.R. Tolkien" 在所有
author
count(/books/book/author[.="J.R.R. Tolkien"]/preceding-sibling::author) + 1
这个表达式的工作原理是:
/books/book/author[.="J.R.R. Tolkien"]
author
/preceding-sibling::author
author
author
count(...)
+ 1
author
author
如果找不到匹配的值,则第一个步骤将返回一个空节点集,
count()
更好的方法可能是使用变量和递归模板(如果你的XPath处理器支持扩展函数或模板):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:variable name="search_value" select="'J.R.R. Tolkien'"/>
<xsl:variable name="authors" select="/books/book/author"/>
<xsl:value-of select="find_index($authors, $search_value, 1)"/>
</xsl:template>
<xsl:template name="find_index">
<xsl:param name="nodes"/>
<xsl:param name="value"/>
<xsl:param name="index"/>
<xsl:choose>
<xsl:when test="not($nodes)">
<!-- Not found -->
</xsl:when>
<xsl:when test="$nodes[1] = $value">
<xsl:value-of select="$index"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="find_index">
<xsl:with-param name="nodes" select="$nodes[position() > 1]"/>
<xsl:with-param name="value" select="$value"/>
<xsl:with-param name="index" select="$index + 1"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>这个XSLT代码定义了一个名为
find_index
index-of()
index-of()
例如,如果序列包含节点集合,并且要查找的 "value" 也是一个节点集合,那么
index-of()
index-of()
考虑以下XML:
<root>
<items>
<item id="1">A</item>
<item id="2">B</item>
<item id="3">C</item>
</items>
<search>
<item id="2">B</item>
</search>
</root>尝试查找
<search/item>
<items/item>
index-of(/root/items/item, /root/search/item)
即使
<items/item>
<search/item>
为了解决这个问题,需要将复杂数据类型转换为简单类型,例如字符串,然后再使用
index-of()
string()
index-of(/root/items/item/string(), /root/search/item/string())
但是,这种方法只适用于节点集合可以转换为有意义的字符串表示形式的情况。 对于更复杂的数据类型,可能需要使用其他方法来实现类似的功能,例如自定义函数或扩展函数。
此外,在某些XPath实现中,
index-of()
index-of()
以上就是XPath的index-of()函数怎么查找位置?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号