From attributes to child elements

Another context in which makes sense to use the xsl:copy element (I'm in XSLT with Saxon mode, if you wonder) is where you want to do just the opposite of the previous post. There we transformed child elements in attributes, here we are about to create child elements from attributes.

Want we want to do now, actually, is reversing the transformation we have done in the previous post. Now we get in input what was the expected output, where the Person elements have two attributes and no child nodes, and we want in output an XML where Person elements are with no attributes but child nodes instead.

Here is the transformation we are going to apply:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="" version="2.0">
<xsl:template match="/">
<xsl:apply-templates select="/People/Person"/>

<xsl:template match="Person">
<xsl:copy> <!-- 1 -->
<xsl:element name="FirstName"> <!-- 2 -->
<xsl:value-of select="@FirstName"/> <!-- 3 -->
<xsl:element name="LastName">
<xsl:value-of select="@LastName"/>


1. Again, we are generating a stripped-down copy of the current input node.
2. As a child node to the newly generated Person, we create a FirstName element.
3. And as value we use the attribute (notice the @ sign) FirstName of the input Person element.
And then the same for the LastName.

More information on XSLT and Saxon in chapter eight of Beginning XML by David Hunter et al. (Wrox).

No comments:

Post a Comment