tags:

views:

37

answers:

1

Hi

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?

+3  A: 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

    <!--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>
Mads Hansen
+1 for the exact answer. I have only one issue with your writing style: it is always better not to use a reverse axis, if possible, in an XPath expression and particularly in match patterns. Instead of `*[../@id]` one can write: `*[@id]/*` . Not only is this shorter, but it is much more understandable.
Dimitre Novatchev
@Dimitre - Thanks for the suggestion. It does read easier that way. Do you happen to know whether forward axis XPATH statements are generally more performant or is it mostly a concern of style/convention?
Mads Hansen
@Mads Hansen: Also, if you match last attribute for an element whos father has @id, you could reduce the template to just two `copy`
Alejandro
@Mads Hansen: I think that forard axis only expressions yield much better results when streaming a large XML document.
Dimitre Novatchev
I would like to thank everybody for their suggestions here. Mads, I am just learning Xsl and being able to see your code for this solution has taught me more than I have learned in the last 2 days struggling with this. I really appreciate it. This was exactly what I was trying to learn. Thanks again.
Richard O'Neil