问题
I thought this ought to be simple to find, yet after some searching I found this might be nice to define clearly.
In my XSD I've defined an enum, derived from string. In a complex type I've defined and attribute that refers to this enum, with a default value.
In my XSL I wish to display the default value of this attribute for elements whose attribute is not explicitly set.
The XSD:
<xs:complexType name="foo">
<xs:attribute name="bar" type="responsecodes:barType" default="default"/>
</xs:complexType>
<xs:simpleType name="barType">
<xs:restriction base="xs:string">
<xs:enumeration value="default">
<xs:annotation>
<xs:documentation xml:lang="en-us">Default bar.</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="chocolate">
<xs:annotation>
<xs:documentation xml:lang="en-us">A chocolate ...bar</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
The XML:
....
<foo/>
<foo bar="default"/>
<foo bar="chocolate"/>
....
I'd expect the XSL to be: (more or less)
<ol>
<xsl:for-each select="/foo">
<li>BarType: '<xsl:value-of select="@bar" />'</li>
</xsl:for-each>
</ol>
Now when I display this style XML file, the value of the 'bar' attribute is empty for the non-specified value, while I'd wish to display (or select on) the default value.
Now:
- BarType: ''
- BarType: 'default'
- BarType: 'chocolate'
Desired:
- BarType: 'default'
- BarType: 'default'
- BarType: 'chocolate'
Now this ought to be quite simple, no?
回答1:
Maybe I'm overgeneralizing, but if you want to load the default from the schema, you would need something along the lines of this:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
>
<xsl:variable name="schema" select="
document('responsecodes.xsd')
" />
<xsl:variable name="DefaultBar" select="
$schema//xs:complexType[@name='foo']/xs:attribute[@name='bar']/@default
" />
<xsl:template match="foo">
<li>
<xsl:text>BarType: '</xsl:text>
<xsl:choose>
<xsl:when test="@bar">
<xsl:value-of select="@bar" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$DefaultBar" />
</xsl:otherwise>
</xsl:choose>
<xsl:text>'</xsl:text>
</li>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/1865685/display-xsd-defined-default-value-of-attribute-using-xsl