2012-12-30 137 views
2

我想知道XSLT是否有修改/添加屬性值的方法。如何使用XSLT修改XML屬性?

現在我簡單地替換屬性值:

<a class="project" href="#"> 
    <xsl:if test="new = 'Yes'"> 
    <xsl:attribute name="class">project new</xsl:attribute> 
    </xsl:if> 
</a> 

但我不喜歡的project在第2行的重複是沒有更好的方法來做到這一點,例如簡單地添加new在屬性的末尾?

感謝您的幫助!

回答

3

你可以把ifattribute,而不是其他方式輪內:

<a href="#"> 
    <xsl:attribute name="class"> 
    <xsl:text>project</xsl:text> 
    <xsl:if test="new = 'Yes'"> 
     <xsl:text> new</xsl:text> 
    </xsl:if> 
    </xsl:attribute> 
</a> 

<xsl:attribute>可以包含任何有效的XSLT模板(包括for-each循環,應用其他模板等),唯一的限制實例化該模板只能生成文本節點,而不是元素,屬性等。屬性值將是所有這些文本節點的串聯。

+0

謝謝。這個解決方案其實很簡單,所以正是我所期待的。謝謝你,新年快樂! – Tintin81

0

在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"/> 

說明

  1. 使用AVT(屬性值模板)

  2. 要選擇基於condi的字符串在XPath 1.0中,可以使用substring函數並指定一個表達式,當條件爲true()時,該表達式的計算結果爲1,並且該表達式的值大於字符串的長度 - otherwize。

  3. 我們使用的事實,在XPath中1.0 *(乘)操作者的任何參數被轉換爲一個數字,並且number(true()) = 1number(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"/> 

說明

  1. 正確使用AVT

  2. 正確使用sequences

  3. 正確使用XSLT current()函數。

+0

非常感謝。這次我和Ian的解決方案一起去了,因爲我對XSLT還很陌生,但我可能會在以後回到你的想法。祝你有個好的一天! – Tintin81