starts-with()函数用于判断字符串是否以指定前缀开头并返回布尔值,其语法为starts-with(string1, string2);在xml文档中可用来选择title以"the"开头的book元素,如//book[starts-with(title, 'the')]将匹配id为"bk101"和"bk103"的元素;处理大小写不敏感匹配时可通过translate()函数统一转换大小写,例如//book[starts-with(translate(title, 'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'), 'the')];常见应用场景包括根据url、id、class、日志级别或电话号码前缀筛选元素,如选择src属性以'https://example.com/images/product_'开头的img元素;可结合and、or运算符与其他函数如contains()、string-length()、substring()实现复合条件匹配,例如//book[starts-with(title, 'the') and starts-with(author, 'j.')]表示同时满足标题以"the"开头且作者以"j."开头的book元素,但应避免过度复杂化表达式以保证性能。

XPath 的
starts-with()
true
false
使用
starts-with()
XPath
starts-with()
starts-with(string1, string2)
其中:
string1
string2
假设我们有以下 XML 文档:
<books>
<book id="bk101">
<title>The Hitchhiker's Guide to the Galaxy</title>
<author>Douglas Adams</author>
</book>
<book id="bk102">
<title>A Brief History of Time</title>
<author>Stephen Hawking</author>
</book>
<book id="bk103">
<title>The Lord of the Rings</title>
<author>J.R.R. Tolkien</author>
</book>
</books>要选择所有标题以 "The" 开头的
book
//book[starts-with(title, 'The')]
这将返回
id
book
解决方案
starts-with()
starts-with(string1, string2)
string1
string2
starts-with()
string1
string2
starts-with()
translate()
starts-with()
例如,要选择所有标题以 "the" (不区分大小写) 开头的
book
//book[starts-with(translate(title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'the')]
这里,
translate(title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
title
starts-with()
starts-with()
starts-with()
举个实际的例子,假设你在抓取一个电商网站,商品的图片 URL 可能是
https://example.com/images/product_123.jpg
https://example.com/images/product_456.jpg
starts-with()
//img[starts-with(@src, 'https://example.com/images/product_')]
starts-with()
starts-with()
and
or
and
or
starts-with()
book
//book[starts-with(title, 'The') and starts-with(author, 'J.')]
contains()
contains()
starts-with()
contains()
book
//book[starts-with(title, 'The') and contains(title, 'History')]
string-length()
string-length()
starts-with()
string-length()
substring()
substring()
需要注意的是,过度复杂的 XPath 表达式可能会降低性能,因此在实际应用中需要权衡复杂性和性能。 编写清晰、简洁的 XPath 表达式,并尽可能利用索引和缓存来提高查询效率。
以上就是XPath的starts-with()函数如何匹配开头字符串?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号