這是一個非常簡單的方式做條件處理使用XSLT模式匹配的強大功能和專門的「推」的風格,而這甚至避免了需要使用條件的說明,如<xsl:if>
或<xsl:choose>
:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/root/diagram[graph[1]/@color]">
Graph[1] has color
</xsl:template>
<xsl:template match="/root/diagram[not(graph[1]/@color)]">
Graph[1] has not color
</xsl:template>
</xsl:stylesheet>
當該變換被應用在下面的XML文檔:
<root>
<diagram>
<graph color= "#ff00ff">
<xaxis>1 2 3 12 312 3123 1231 23 </xaxis>
<yaxis>1 2 3 12 312 3123 1231 23 </yaxis>
</graph>
<graph>
<xaxis>101 102 103 1012 10312 103123 1</xaxis>
<yaxis>101 102 103 1012 10312 103123 1</yaxis>
</graph>
</diagram>
</root>
的希望,正確的結果產生:
Graph[1] has color
當相同的變換應用此XML文檔上:
<root>
<diagram>
<graph>
<xaxis>101 102 103 1012 10312 103123 1</xaxis>
<yaxis>101 102 103 1012 10312 103123 1</yaxis>
</graph>
<graph color= "#ff00ff">
<xaxis>1 2 3 12 312 3123 1231 23 </xaxis>
<yaxis>1 2 3 12 312 3123 1231 23 </yaxis>
</graph>
</diagram>
</root>
再次想和正確的結果產生:
Graph[1] has not color
可以自定義此解決方案,並將第一個模板中所需的任何代碼以及第二個模板中的必要代碼放入。
你得到什麼錯誤? – 2010-11-10 16:33:28
您是否使用過'xsl:choose' ::('xsl:when' + |'xsl:otherwise')指令? – 2010-11-10 16:37:54
是的,我使用了xsl:choose ... xsl:when + xsl:否則條件是徒勞的。 – srivatsa 2010-11-10 16:41:27