问题
I have the following XSD which was generated by VS from an example XML file:
<xs:element name="amperage_rating">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="unit" type="xs:string" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
which demands a numeric value. But sometimes the value is not known and this must also be allowed:
<amperage_rating unit="A"></amperage_rating>
I've tried nillable="true" but it had no effect. I have also tried to define a union with a 0-length string but that keeps saying it is "not supported in this context".
So how do I adjust the XSD to allow this?
回答1:
You can combine the two types you wish to allow via xs:union
:
<xs:element name="amperage_rating" type="empty_or_decimal"/>
<xs:simpleType name="empty_or_decimal">
<xs:union memberTypes="empty xs:decimal"/>
</xs:simpleType>
<xs:simpleType name="empty">
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
</xs:restriction>
</xs:simpleType>
回答2:
There are two approaches. One is what @kjhughes suggests: define a union between xs:decimal
and a zero-length-string type. The other, which I personally prefer, is to define a list type with item type xs:decimal
and maxLength 1. Although the effect on validation is exactly the same, I think the list type is easier to use when the schema is used for data typing: certainly with XSLT and XQuery, where atomizing the element will give you a sequence of zero or one decimals.
回答3:
It sounds as if your use case is very like some of the motivating cases for xsi:nil. From your description, it sounds as if you made the element nillable, but then fed it an non-nilled instance of the form
<amperage_rating unit="A"></amperage_rating>
instead of specifying that the element should be nilled:
<amperage_rating unit="A" xsi:nil="true"></amperage_rating>
If you want to modify the type, the methods described by kjhughes and Michael Kay should work fine.
来源:https://stackoverflow.com/questions/37731133/defining-an-xml-element-that-must-be-empty-or-decimal