2013-02-18 69 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