数据类型
或许,对于许多开发人员来讲,XML Schema与XML DTD相比的一个最显著的特征,就是其对数据类型的支持了。这完全是因为XML DTD提供的数据类型只有CDATA 、Enumerated、NMTOKEN 、NMTOKENS等十种内置(built-in)数据类型。这样少的数据类型通常无法满足文档的可理解性和数据交换的需要。XML Schema则不同,它内置了三十七种数据类型,如long,int,short,double等常用的数据类型,并通过将数据类型表示为由value space、lexical space和facet三部分组成的三元组而获得更大的灵活性。但是, XML Schema数据类型的真正灵活性来自于其对用户自定义类型的支持。XML Schema提供两种方式来实现数据类型的定义。
1)简单类型定义(simpleType),即在XML Schema内置的数据类型基础上或其它由XML Schema内置的数据类型继承或定义所得到的简单的数据类型(simpleType)基础上,通过restriction,list 或者 union方式定义新的数据类型。
例如:
源码1 restriction方式的定义
<simpleType name='Sku'>
<restriction base='string'>
<pattern value='\d{3}-[A-Z]{2}'/>
</restriction>
</simpleType>
源码2 list方式的定义
<simpleType name='listOfDouble'>
<list itemType='double'/>
</simpleType>
源码3 union方式的定义
<xsd:attribute name="size">
<xsd:simpleType>
<xsd:union>
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:minInclusive value="1"/>
<xsd:maxInclusive value="12"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="month"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:union>
</xsd:simpleType>
</xsd:attribute>
2) 复合类型定义(complexType),该方法提供了一种功能强大的复杂数据类型定义机制,可以实现包括结构描述在内的复杂的数据类型。下面是一个以complexType定义实现关系模式中表结构的例子,设有表T_C_Type(Psign,Count),其中Psign为CHAR数据类型,Count为NUMBER数据类型。则有:
源码4 complexType定义
<!--表结构类型定义-->
<complexType name="T_C_Type">
<sequence minOccurs="0" maxOccurs="unbounded">
<element name="Psign">
<complexType>
<simpleContent>
<restriction base="string">
<attribute name="value" type="string"/>
</restriction>
</simpleContent>
</complexType>
</element>
<element name="Count" minOccurs="0">
<complexType>
<complexContent>
<restriction base="anyType">
<attribute name="value" type="int" use="optional"/>
</restriction>
</complexContent>
</complexType>
</element>
</sequence>
</complexType>
不仅如此,XML Schema还允许元素的内容取空值,这一点可以扩大XML Schema对数据情况的描述范围,而XML DTD则无能为力。例如:
源码5 XML Schema 元素取空值的定义 <element name='test' nullable='true'/>