I have a very specific problem when I want to get the default attribute value of an element, as shown in the example below.
Each input XML element contains several child names, one of which represents the primary name, which is the default attribute value (type = 'main') and the other secondary name (type = 'short'). The primary name does not have the value of the "main" attribute. The following is an example of XML input with the first name element deliberately commented to illustrate the problem below:
<?xml version="1.0"?> <food_list> <food_item> <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 NameType is as follows:
<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>
XSLT to convert input XML and extract primary name and short name 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 converting input XML, the primary name for the first battery is incorrectly selected from the element with type = 'short'. Question: How do you limit the first expression to a value in xslt to only get name values ββwhen a default element is defined?
source share