2010-10-15 16 views
9

如果我有這樣的一個源文件:你如何與XSLT進行通配符匹配?

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

我可以做我的樣式表與他們的名字字符串「_monkey」只選擇動物XPATH表達式?

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

+0

你用什麼版本的XSLT的? – 2010-10-15 13:08:57

+0

好問題,+1。查看我對XSLT 1.0和XSLT 2.0解決方案的回答。:) – 2010-10-15 13:19:46

+0

@iasha我目前使用1.0,但有興趣瞭解兩者之間的差異。 – 2010-10-15 13:31:28

回答

26

我可以做一個XPath表達式我 樣式與在 他們的名字字符串「_monkey」只選擇 動物?

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

此通配符意味着 「_monkey」 結尾,不含有 「_monkey」 的字符串的字符串。

使用

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

上面使用標準的XPath 2.0功能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')] 

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

取決於一個人的特定需求(例如,你真的意味着「包含」而不是「結尾」),該功能contains()starts-with()substring()也可能是有用的:

contains(someString, someTargetString) 

starts-with(someString, someTargetString) 

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

最後,<xsl:templates>match屬性不需要包含絕對XPath表達式 - 只是建議使用指定足夠上下文的相對XPath表達式。

因此,上述用於匹配表達式將東西如下:

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

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

很好的答案。謝謝! – 2010-10-15 13:32:55

+3

+1有關詳細解釋。 – 2010-10-15 14:16:24

+0

我該如何使用它:在XSLT 1.0中匹配(名稱(。),'grp')]「>'' Si8 2015-10-28 17:32:29