xml 你如何用 XSLT 进行通配符匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3942394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you do wildcard matches with XSLT?
提问by Chris Huang-Leaver
If I have a source file like this:
如果我有这样的源文件:
<animal name="fred_monkey" />
<animal name="jim_banana" />
<animal name="joe_monkey" />
Can I do an XPATH expression in my stylesheet which selects only the animals with the string '_monkey' in their name?
我可以在我的样式表中做一个 XPATH 表达式,它只选择名称中带有字符串 '_monkey' 的动物吗?
e.g. wildcard match '*_monkey' ?
例如通配符匹配 '*_monkey' ?
回答by Dimitre Novatchev
Can I do an XPATH expression in my stylesheet which selects only the animals with the string '_monkey' in their name?
e.g. wildcard match '*_monkey' ?
我可以在我的样式表中做一个 XPATH 表达式,它只选择名称中带有字符串 '_monkey' 的动物吗?
例如通配符匹配 '*_monkey' ?
This wildcard means a string ending with"_monkey", not a string containing"_monkey".
此通配符表示以“_monkey”结尾的字符串,而不是包含“_monkey”的字符串。
Use:
使用:
//animal[ends-with(@name, '_monkey')]
The above uses the standard XPath 2.0 function ends-with()and is thus available only in XSLT 2.0.
以上使用标准 XPath 2.0 函数ends-with(),因此仅在 XSLT 2.0 中可用。
In XSLT 1.0 use the following XPath 1.0 expression:
在 XSLT 1.0 中使用以下 XPath 1.0 表达式:
//animal[substring(@name, string-length(@name) -6)='_monkey']
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 animalelements 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:
不建议使用//缩写,因为这可能会导致评估效率低下。只要知道 XML 文档的结构,就使用更具体的位置测试链。例如,如果animal元素都是 XML 文档顶部元素的所有子元素,那么以下 XPath(分别为 2.0 或 1.0)表达式可能更有效:
/*/animal[ends-with(@name, '_monkey')]
and
和
/*/animal[substring(@name, string-length(@name) -6)='_monkey']
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(), starts-with()andsubstring()也可能有用:
contains(someString, someTargetString)
starts-with(someString, someTargetString)
substring(someString, start-index, length) = someTargetString
Finally, the matchattribute 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.
最后, 的match属性<xsl:templates>不需要包含绝对 XPath 表达式——推荐使用指定足够上下文的相对 XPath 表达式。
Thus, the above used as match expressions will be something as:
因此,上面用作匹配表达式的内容将是:
<xsl:template match="animal[ends-with(@name, '_monkey')]">
and
和
<xsl:template match=
"animal[substring(@name, string-length(@name) -6)='_monkey']">

