Lisa
Lisa

Reputation: 77

How to rename child element attribute and modify attribute value using xslt

There is this certain element in my xml:

<para><link href="D52871.dita">abc</link>
</para>

I want the output to be

<para><link id="D52871">abc</link>
</para>

I have used identity transform in the beginning to copy everything. I tried this code snippet

<xsl:template match="link/@href">
  <xsl:attribute name="id">
    <xsl:value-of select="."/>
  </xsl:attribute>
</xsl:template> 

but it's not working probably because I need to specify that link element is inside para. Have tried few approaches to include that but none worked so far.

Upvotes: 0

Views: 964

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

The following works fine for me

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

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

    <xsl:template match="link/@href">
        <xsl:attribute name="id">
            <xsl:value-of select="substring-before(.,'.')"/>
        </xsl:attribute>
    </xsl:template> 

</xsl:stylesheet>

Input:

<?xml version="1.0" encoding="UTF-8"?>
<para>
   <link href="D52871.dita">abc</link>
</para>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<para>
   <link id="D52871">abc</link>
</para>

Upvotes: 1

Related Questions