I have a very specific problem where I want to be able to extract the default attribute value of an element as illustrated in the example below.
Every item in the input XML contains multiple child name elements, one to represent the primary name, which is the default attribute value (type='main') and another secondary name (type='short'). The primary name does not have the attribute value 'main' specified. Here is a sample input XML with the first name element deliberately commented out to illustrate the issue further down:
<?xml version="1.0"?>
<food_list>
<food_item>
<!--name>Apple</name-->
<name type="short">APL</name>
</food_item>
<food_item>
<name>Asparagus</name>
<name type="short">ASP</name>
</food_item>
<food_item>
<name>Cheese</name>
<name type="short">CHS</name>
</food_item>
</food_list>
The XSD for the NameType looks like this:
<complexType name="NameType">
<simpleContent>
<extension base="TextualBaseType">
<attribute name="type" use="optional" default="main">
<simpleType>
<restriction base="NMTOKEN">
<enumeration value="main"/>
<enumeration value="short"/>
<enumeration value="alternative"/>
</restriction>
</simpleType>
</attribute>
</extension>
</simpleContent>
</complexType>
The XSLT to transform the input XML and extract the Primary name and the Short name is below:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="food_list">
<table>
<tr style="background-color:#ccff00">
<th>Food Name</th>
<th>Food Short Name</th>
</tr>
<xsl:for-each select="food_item">
<tr style="background-color:#00cc00">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="name[@type='short']"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
When the input XML is transformed the Primary name for the first food item is wrongly picked up from the element with type='short'. Question: How do you restrict the first value-of statement in the xslt to only pick up name values when a default element is defined?