XML Schema 提供了一組豐富的內建數據類型,用來定義元素中允許的類型。以下介紹幾種通用型別與相關概念。
基本類型是各數據類型的構成基石,可據此構造自訂型別:
boolean(1 為 true、0 為 false)、dateTime(如 2005-3-18T14:48:12,時間部分可選)、decimal(任意精度十進位數)、string(字元資料)、int(-2,147,483,648 到 2,147,483,648 的整數)、nonNegativeInteger(≥0)、nonPositiveInteger(≤0)、short(-32768 到 32767)。
示例:
<xsd:element name="rate" type="xsd:decimal" /> <xsd:attribute name="lastUpdated" type="xsd:dateTime" />
僅靠內建類型往往不足以限制數值,這時需要「約束」:enumeration(列舉指定值)、fractionDigits(小數最大位數)、length(長度)、minExclusive/maxExclusive(開區間上下限)、minLength/maxLength(長度範圍)、minInclusive/maxInclusive(閉區間範圍)、pattern(須符合的正則表達式)、totalDigits、whiteSpace(preserve/replace/collapse)等。
套用約束時使用 restriction 元素,其 base 屬性設為某內建 XSD 類型或既有簡單類型:
<xsd:restriction base="xsd:string"> <xsd:minLength value="4" /> <xsd:maxLength value="10" /> </xsd:restriction> <xsd:restriction base="xsd:int"> <xsd:minInclusive value="1" /> <xsd:maxInclusive value="100" /> </xsd:restriction>
簡單類型用 simpleType 元素定義,它基本上是一個值或一組值,不能包含元素或屬性:
<xsd:simpleType name="personsName"> <xsd:restriction base="xsd:string"> <xsd:minLength value="4" /> <xsd:maxLength value="8" /> </xsd:restriction> </xsd:simpleType> <xsd:element name="first" type="personsName" />
複雜類型用 complexType 定義,可包含屬性與元素,常與 simpleType 搭配使用:
<xsd:complexType name="FullName"> <xsd:sequence> <xsd:element name="first" type="PersonsFirstname" minOccurs="0" maxOccurs="1" default="John" /> <xsd:element name="middle" type="xsd:string" minOccurs="0" maxOccurs="unbounded" nillable="true" /> <xsd:element name="last" type="xsd:string" minOccurs="1" maxOccurs="1" default="Doe" /> </xsd:sequence> <xsd:attribute name="title" type="PersonsTitle" default="Mr." /> </xsd:complexType>
元素集可用 group 元素分組,屬性集則用 attributeGroup:
<xsd:group name="CityChoice"> <xsd:choice> <xsd:element name="Beijing" type="xsd:string" /> <xsd:element name="Shanghai" type="xsd:string" /> </xsd:choice> </xsd:group> <xsd:attributeGroup name="contactAttribs"> <xsd:attribute name="city" type="xsd:string" /> <xsd:attribute name="age" type="xsd:string" /> </xsd:attributeGroup>
內容模型可限制 XML 中能使用的元素、屬性與類型:
any(預設模型,可含文字、元素與空格,namespace 可取 ##any、##other、##local、##targetNamespace;processContents 可取 strict、lax、skip)、empty(禁止子元素與文字,僅能有屬性)、element、mixed(在 complexType 上設 mixed="true",可混雜文字與元素)。
例如 mixed 內容模型:
<xsd:element name="contact"> <xsd:complexType mixed="true"> <xsd:sequence> <xsd:element name="first" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element>
其有效實例可寫成:<contact>My first name is<first>Santld</first>.</contact>,其中 contact 同時包含文字與元素。