2

I have an XML file which has an @url attribute for the element <matimage>. Currently there is a certain image name in the @url attribute, say triangle.png. I want to apply XSLT and modify this URL so that it would be something like assets/images/triangle.png.

I tried the following 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>

As a first step I tried to replace the old value with a new value but that didn't seem to work. Please tell me how to prepend or append a new value to the existing value of the @url attribute.

Here is the sample XML:

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

Desired output:

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

1 Answer 1

5

A solution for what you are trying to achieve could be:

<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>
Sign up to request clarification or add additional context in comments.

2 Comments

I would like to add a suggestion here. Using <xsl:copy> as the parent of concat statement doesn't work. I used this element <xsl:attribute name="url"> and it rendered fine.
Thanks for the correction. <xsl:copy> just copies the attribute node as it is (with the value included). I was testing the stylesheet with the wrong XML file so I was getting the result right. Little lapsus...sorry and thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.