在XSLT 1.0可以使用此一襯墊:
<a class="project{substring(' new', 5 - 4*(new = 'Yes'))}"/>
下面是一個完整變換:
<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="/*">
<a class="project{substring(' new', 5 - 4*(new = 'Yes'))}"/>
</xsl:template>
</xsl:stylesheet>
當在下面的XML文檔被應用於這種轉變:
<t>
<new>Yes</new>
</t>
想要的,正確的結果產生:
<a class="project new"/>
說明:
使用AVT(屬性值模板)
要選擇基於condi的字符串在XPath 1.0中,可以使用substring函數並指定一個表達式,當條件爲true()
時,該表達式的計算結果爲1,並且該表達式的值大於字符串的長度 - otherwize。
我們使用的事實,在XPath中1.0 *
(乘)操作者的任何參數被轉換爲一個數字,並且number(true()) = 1
和number(false()) = 0
II。 XSLT 2。0溶液:
使用此一襯墊:
<a class="project{(' new', '')[current()/new = 'Yes']}"/>
下面是一個完整變換:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<a class="project{(' new', '')[current()/new = 'Yes']}"/>
</xsl:template>
</xsl:stylesheet>
當在同一個XML文檔(上文)施加再次相同的想要的,產生正確的結果:
<a class="project new"/>
說明:
正確使用AVT。
正確使用sequences。
正確使用XSLT current()
函數。
謝謝。這個解決方案其實很簡單,所以正是我所期待的。謝謝你,新年快樂! – Tintin81