2

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?

1 Answer 1

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

5 Comments

+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 - 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?
Also, if you match last attribute for an element whos father has @id, you could reduce the template to just two copy
I think that forard axis only expressions yield much better results when streaming a large XML document.
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.

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.