2013-02-18 46 views
2

我有一個XML文件,該文件具有<matimage>元素的@url屬性。當前在@url屬性中存在某個圖像名稱,例如triangle.png。我想申請XSLT並修改此URL,以便它可以像assets/images/triangle.png使用XSLT修改XML文檔的屬性

我嘗試以下XSLT:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" /> 

    <!-- Copy everything --> 
    <xsl:template match="*"> 
    <xsl:copy> 
    <xsl:copy-of select="@*" /> 
    <xsl:apply-templates /> 
    </xsl:copy> 
    </xsl:template> 

<xsl:template match="@type[parent::matimage]"> 
    <xsl:attribute name="uri"> 
    <xsl:value-of select="NEW_VALUE"/> 
    </xsl:attribute> 
</xsl:template> 
</xsl:stylesheet> 

第一步我試圖用一個新值來代替舊值,但似乎並沒有工作。請告訴我如何在@url屬性的現有值前添加或附加新值。

下面是示例XML:

<material> 
    <matimage url="triangle.png"> 
     Some text 
    </matimage> 
    </material> 

所需的輸出:

<material> 
    <matimage url="assets/images/triangle.png"> 
     Some text 
    </matimage> 
    </material> 

回答

5

一種你希望實現什麼可以解決:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes"/> 

    <!-- Identity template : copy elements and attributes --> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()" /> 
     </xsl:copy> 
    </xsl:template> 

    <!-- Match all the attributes url within matimage elements --> 
    <xsl:template match="matimage/@url"> 
     <xsl:attribute name="url"> 
      <!-- Use concat to prepend the value to the current value --> 
      <xsl:value-of select="concat('assets/images/', .)" /> 
     </xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 
+1

我想補充這裏有一個建議。使用''作爲'concat'語句的父項不起作用。我使用了這個元素'',它顯示正常。 – jaykumarark 2013-02-18 12:34:12

+0

感謝您的更正。 只是複製屬性節點(包括值)。我正在用錯誤的XML文件測試樣式表,所以我得到了正確的結果。小傷口...抱歉,謝謝 – 2013-02-18 12:44:17