Defining an XML element that must be empty or decimal

跟風遠走 提交于 2019-12-02 12:09:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!