我可以在我的程序中执行 XPATH 表达式吗?
样式表仅选择
带有字符串“_monkey”的动物
他们的名字?
例如通配符匹配“*_monkey”?
这个通配符的意思是以以下结尾的字符串“_monkey”,不是一个字符串包含“_猴”。
Use:
//animal[ends-with(@name, '_monkey')]
上面使用了标准的XPath 2.0函数ends-with() http://www.w3.org/TR/xpath-functions/#func-ends-with因此仅在 XSLT 2.0 中可用。
在 XSLT 1.0 中使用以下 XPath 1.0 表达式:
//animal[substring(@name, string-length(@name) -6)='_monkey']
不建议使用//
缩写,因为这可能会导致评估效率低下。只要 XML 文档的结构已知,就可以使用更具体的位置链测试。例如,如果animal
元素都是 XML 文档顶部元素的子元素,那么以下 XPath(分别为 2.0 或 1.0)表达式可能会更有效:
/*/animal[ends-with(@name, '_monkey')]
and
/*/animal[substring(@name, string-length(@name) -6)='_monkey']
根据一个人的具体需求(例如,您真正的意思是“包含”而不是“结束于”),功能contains() http://www.w3.org/TR/xpath/#function-contains, starts-with() http://www.w3.org/TR/xpath/#function-starts-with and substring() http://www.w3.org/TR/xpath/#function-substring也可能有用:
contains(someString, someTargetString)
starts-with(someString, someTargetString)
substring(someString, start-index, length) = someTargetString
最后,match
的属性<xsl:templates>
不需要包含绝对 XPath 表达式-- 建议仅使用指定足够上下文的相对 XPath 表达式。
因此,上面用作匹配表达式的内容将如下所示:
<xsl:template match="animal[ends-with(@name, '_monkey')]">
and
<xsl:template match=
"animal[substring(@name, string-length(@name) -6)='_monkey']">