Okay, I've just started with XSLT this weekend. I bought a book and read some articles and am just starting to really get into it.
I have a question. Purely for the purpose of an exercise I wish to iterate through an XML document and convert some child elements to attributes for a parent element. I know it's generally bad-practice to go overboard with attributes but I am doing this purely as an exercise, not for any real-life purpose.
As an example I would like this...
Code:
<name>
<first>Fred</first>
<middle>J.</first>
<last>Bloggs</last>
</name>
...to become...
Code:
<name first="Fred" middle="J." last="Bloggs" />
Here's the XML document
Code:
<?xml version="1.0" encoding="UTF-8"?>
<people>
<name>
<first>John</first>
<middle>Fitzgerald Johansen</middle>
<last>Doe</last>
</name>
<name>
<first>Franklin</first>
<middle>D.</middle>
<last>Roosevelt</last>
</name>
<name>
<first>Alfred</first>
<middle>E.</middle>
<last>Neuman</last>
</name>
<name>
<first>John</first>
<middle>Q.</middle>
<last>Public</last>
</name>
<name>
<first>Jane</first>
<middle/>
<last>Doe</last>
</name>
</people>
and here's the Stylesheet
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="UTF-8" />
<!-- root document template -->
<xsl:template match="/">
<people>
<!-- execute any templates defined for elements which are a child of <people> -->
<xsl:apply-templates />
</people>
</xsl:template>
<!-- match any <name> elements -->
<xsl:template match="name">
<!-- create an element called name and use the attribute set called attribs -->
<xsl:element name="name" use-attribute-sets="attribs" />
</xsl:template>
<xsl:attribute-set name="attribs">
<xsl:attribute name="{local-name()}"><xsl:value-of select="." /></xsl:attribute>
<!-- THIS BIT WORKS WHEN UNCOMMENTED!
create three attributes, assign the value of the <first>, <middle>, or <last> elements to the attribute
<xsl:attribute name="first"><xsl:value-of select="first" /></xsl:attribute>
<xsl:attribute name="middle"><xsl:value-of select="middle" /></xsl:attribute>
<xsl:attribute name="last"><xsl:value-of select="last" /></xsl:attribute>
-->
</xsl:attribute-set>
</xsl:stylesheet>
I can get it to work when I explicitly refer to the element names in the attribute-set, but not if I wish to be a bit more dynamic and use the local-name() function. Can someone please explain where I am going wrong here?
Many Thanks