Richard O'Neil
Richard O'Neil

Reputation: 163

How to add specific attribute to every node in Xml file using Xsl?

I have a bit of Xml that looks something like this:

<books>
  <book id="1">
    <name>My book</name>
    <author>My author</author>
  </book>
  <book id="2">
    <name>My other book</name>
    <author>My other author</author>
  </book>
</books>

I would like to have it look like:

<books>
  <book id="1">
    <name id="1">My book</name>
    <author id="1">My author</author>
  </book>
  <book id="2">
    <name id="2">My other book</name>
    <author id="2">My other author</author>
  </book>
</books>

Could somebody point me in the correct direction?

Upvotes: 2

Views: 1153

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66723

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

    <!--Standard identity template that copies all content -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--special template for elements who's parent has an @id -->
    <xsl:template match="*[../@id]">
        <xsl:copy>
            <xsl:copy-of select="../@id" />
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 4

Related Questions