xml - 如何使 complexType 为空或不超过 100 个值?
问题描述
我可以再次使用您的帮助,这次使用 XML Schema……这是我必须做的练习:
定义描述酒店的 XML 模式。
Document's root is "hotel" element and it has following other elements:
1)name <hotel's name type:string>
2)rooms <list of "type" elements, which can be empty but with not more
than 100 elements of type RoomType which contain:
1)type <room's type, it's value is one of {single, double,triple}>
2)number <number of rooms of specified type in the hotel>
3)forSmokers<optional element, number of rooms where smokers are allowed>
这是我的代码:
<?xml version = "1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name = "hotel">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string"/>
<xs:element name = "rooms" type = "roomType"/>
<xs:element name = "forSmokers" type = "xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "roomType">
<xs:sequence>
<xs:element name = "room'stype" type = "roomTypes" minOccurs = "0" maxOccurs = "100"/>
<xs:element name = "number" type = "xs:positiveInteger" minOccurs = "0" maxOccurs = "100"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name = "roomTypes">
<xs:restriction base = "xs:string">
<xs:enumeration value = "single"/>
<xs:enumeration value = "double"/>
<xs:enumeration value = "triple"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
现在有了这个 XML 文件,验证就顺利进行了:
<?xml version = "1.0"?>
<hotel>
<name>NomeHotel</name>
<rooms>
<room'stype>singola</room'stype>
<number>1</number>
</rooms>
<forSmokers>22</forSmokers>
</hotel>
我的问题是:现在,如果我在现有标签中添加<room'stype>
和标签,验证会返回错误。我需要房间标签来允许 0 个元素(所以它可以是空的)但它不能有超过 100 个元素,我必须如何修改代码才能实现这一点?<number
<rooms>
对不起,很长的问题,只是想清楚。谢谢
解决方案
您必须将架构更改为:
<?xml version = "1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name = "hotel">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string"/>
<xs:element name = "rooms" type = "roomType"/>
<xs:element name = "forSmokers" type = "xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "roomType">
<xs:sequence>
<xs:element name = "roomstype" type = "roomTypes" minOccurs = "0" maxOccurs = "100"/>
<xs:element name = "number" type = "xs:positiveInteger" minOccurs = "0" maxOccurs = "100"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name = "roomTypes">
<xs:restriction base = "xs:string">
<xs:enumeration value = "singola"/>
<xs:enumeration value = "double"/>
<xs:enumeration value = "triple"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
我注意到两件事:
- 元素名称不能包含
'
- 在 xml 中有
singola
,但在架构中是single