你如何用 XSLT 进行通配符匹配? [英] How do you do wildcard matches with XSLT?

查看:32
本文介绍了你如何用 XSLT 进行通配符匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的源文件:

If I have a source file like this:

<animal name="fred_monkey" />
<animal name="jim_banana" />
<animal name="joe_monkey" />

我可以在我的样式表中做一个 XPATH 表达式,只选择名称中带有字符串_monkey"的动物吗?

Can I do an XPATH expression in my stylesheet which selects only the animals with the string '_monkey' in their name?

例如通配符匹配 '*_monkey' ?

e.g. wildcard match '*_monkey' ?

推荐答案

我可以在我的文件中做一个 XPATH 表达式吗?样式表只选择带有字符串_monkey"的动物他们的名字?

Can I do an XPATH expression in my stylesheet which selects only the animals with the string '_monkey' in their name?

例如通配符匹配 '*_monkey' ?

e.g. wildcard match '*_monkey' ?

此通配符表示_monkey"结尾的字符串,而不是包含_monkey"的字符串.

This wildcard means a string ending with "_monkey", not a string containing "_monkey".

使用:

//animal[ends-with(@name, '_monkey')]

以上使用标准XPath 2.0函数ends-with(),因此仅在 XSLT 2.0 中可用.

The above uses the standard XPath 2.0 function ends-with() and is thus available only in 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)表达式可能更有效:

It isn't recommended to use the // abbreviation as this may result in inefficient evaluation. Use more specific chain of location tests whenever the structure of the XML document is known. For example, if the animal elements are all children of the top element of the XML document, then the following XPath (2.0 or 1.0, respectively) expressions might be more efficient:

/*/animal[ends-with(@name, '_monkey')]

/*/animal[substring(@name, string-length(@name) -6)='_monkey']

根据一个人的特定需求(例如,您真正的意思是包含"而不是结束于"),功能 contains(), starts-with()substring() 也可能有用:

Depending on one's specific needs (e.g. you really meant "contains" and not "ends with"), the functions contains(), starts-with() and substring() may also be useful:

contains(someString, someTargetString)

starts-with(someString, someTargetString)

substring(someString, start-index, length) = someTargetString

最后,match 属性不需要包含绝对的 XPath 表达式——只是一个建议使用指定足够上下文的相对 XPath 表达式.

Finally, the match attribute of <xsl:templates> doesn't need to contain an absolute XPath expression -- just a relative XPath expression that specifies enough context is recommended to be used.

因此,上面用作匹配表达式的内容将是:

Thus, the above used as match expressions will be something as:

<xsl:template match="animal[ends-with(@name, '_monkey')]">

<xsl:template match=
  "animal[substring(@name, string-length(@name) -6)='_monkey']">

这篇关于你如何用 XSLT 进行通配符匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆