標籤:des 使用 os cti for io
之前我用了比較多的call-template,後來說著說著,突然發現apply-templates在大部分的情境下比call-template好用,也更安全一些。
比如,apply-templates可以通過select屬性來選擇具體要匹配的node-set,如果不存在這樣的node-set,就不進行轉換,這就比call-template安全了一些,因為後者是直接調用,不管存不存在某些節點;其次,apply-templates和call-template一樣,可以通過<xsl:param/>接受參數;此外,當我們定義多個template時,這些templates不可以有重複的name,但可以有重複的match,重複的template通過priority來確定該用哪個template來進行轉換,如果多個template有相同的priority的話,則選擇最後出現的那個。
似乎apply-templates功能比call-template強。就目前我所用到的普通轉換來說,用apply-templates是比較安全的,並且可讀性也會高一些。但是在XSLT 1.0中,如果想要實現像XSLT 2.0中function一樣的功能的話,用call-template就比較方便了,比如遞迴調用(Recursive function)。下面是一個例子:
<xsl:template name=”longest-speech” as=”element(SPEECH)?”>
<xsl:param name=”list” as=”element(SPEECH)*”/>
<xsl:choose>
<xsl:when test=”$list”>
<xsl:variable name=”first” select=”count($list[1]/LINE)” as=”xs:integer”/>
<xsl:variable name=”longest-of-rest” as=”element(SPEECH)?”>
<xsl:call-template name=”longest-speech”>
<xsl:with-param name=”list” select=”$list[position()!=1]“/>
</xsl:call-template>
</xsl:variable>
<xsl:choose>
<xsl:when test=”$first gt count($longest-of-rest/LINE)”>
<xsl:value-of select=”$list[1]“/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select=”$longest-of-rest”/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template match=”/”>
<longest-speech>
<xsl:call-template name=”longest-speech”>
<xsl:with-param name=”list” select=”//SPEECH”/>
</xsl:call-template>
</longest-speech>
</xsl:template>
待轉換的xml是:
<?xml version=”1.0″?>
<SCENE><TITLE>SCENE I. Venice. A street.</TITLE>
<STAGEDIR>Enter RODERIGO and IAGO</STAGEDIR>
<SPEECH>
<SPEAKER>RODERIGO</SPEAKER>
<LINE>Tush! never tell me; I take it much unkindly</LINE>
<LINE>That thou, Iago, who hast had my purse</LINE>
<LINE>As if the strings were thine, shouldst know of this.</LINE>
</SPEECH>
<SPEECH>
<SPEAKER>IAGO</SPEAKER>
<LINE>’Sblood, but you will not hear me:</LINE>
<LINE>If ever I did dream of such a matter, Abhor me.</LINE>
</SPEECH>
etc.
</SCENE>
在關於使用call-template和apply-templates的效能差別上,Sam Judson (Wrox 技術編輯)有言:
In terms of raw performance xsl:call-template is likely to be faster, as you are calling a specific named template, rather than telling the XSLT processor to pick the template which best matches.
There are certainly things you can do with xsl:call-template that you can’t do with xsl:apply-templates, such as recursive templates which are very powerful.
xsl:apply-templates is however the more flexible and extensible, due to its combined use of the match patterns, modes and priorities.
我覺得概括的不錯,言簡意賅,就以此作為結尾吧。