爲了證明這對其他人也有用,下面是我根據邁克爾凱的建議寫的代碼。我寫了一個自定義的compare
函數,它提供了與Xpath 2.0相同的結果。我還爲該問題添加了php
標籤,以便更頻繁地找到它。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:func="http://exslt.org/functions"
xmlns:common="http://exslt.org/common"
xmlns:custom="urn:myCustomFunctions"
exclude-result-prefixes="func common custom"
extension-element-prefixes="func custom">
<xsl:output method="xml"/>
<func:function name="custom:compare">
<xsl:param name="string1"/>
<xsl:param name="string2"/>
<func:result>
<xsl:choose>
<xsl:when test="$string1 = $string2">0</xsl:when>
<xsl:otherwise>
<xsl:variable name="nodes">
<node><xsl:value-of select="$string1"/></node>
<node><xsl:value-of select="$string2"/></node>
</xsl:variable>
<xsl:for-each select="common:node-set($nodes)/*">
<xsl:sort select="."/>
<xsl:choose>
<xsl:when test="position()=1 and .=$string1">-1</xsl:when>
<xsl:when test="position()=1 and .=$string2">1</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:otherwise>
</xsl:choose>
</func:result>
</func:function>
<xsl:template match="/">
<out>
<test1><xsl:value-of select="custom:compare('A', 'B')"/></test1>
<test2><xsl:value-of select="custom:compare('A', 'A')"/></test2>
<test3><xsl:value-of select="custom:compare('C', 'B')"/></test3>
<test4><xsl:value-of select="custom:compare('DD', 'A')"/></test4>
</out>
</xsl:template>
</xsl:stylesheet>
運行這個(與虛擬輸入)的結果是
<?xml version="1.0"?>
<out>
<test1>-1</test1>
<test2>0</test2>
<test3>1</test3>
<test4>1</test4>
</out>
對於那些誰願意來測試這個在PHP自己,這是我使用的代碼:
<?php
$xslt = new XSLTProcessor();
$xslt->importStylesheet(DOMDocument::load('testCompare.xslt'));
$xslt -> registerPHPFunctions();
$xml = new SimpleXMLElement('<test/>');
print $xslt->transformToXML($xml);
?>
謝謝邁克爾 - 不錯的緊湊解決方案。至於XSLT 2.0,有什麼讓我反感 - 'libxslt'是 - 這是'php 5'使用的引擎,我無法改變它。也許在將來,我的託管服務商將使用一個使用XSLT 2.0引擎的PHP版本 - 如果有的話。當然,我真的很想在XSLT 2.0中做所有這些事情 - 實際上我是爲了開發而做的,然後不得不重寫所有內容。我認爲,對於大量的XSLT開發人員來說,不移動到XSLT 2.0的原因是相同的。 – Maestro13
@ Maestro13:Zobra支持XPath 2.0並可作爲PHP擴展使用,請參閱:http://www.ibm.com/developerworks/xml/library/x-zorba/index.html - 就PHP而言,您可以[註冊PHP函數](http://php.net/manual/en/domxpath.registerphpfunctions.php)像'strcmp'用於你的xpath。 – hakre
@hakre謝謝你的信息 - 我會去檢查我的託管服務提供商是否可以激活Zobra。是的,另一種方法是註冊一個自定義php函數,並在xslt中使用它 - 在XSLT戰鬥中,我完全忘記了這一點。 – Maestro13