在 XML Schema 中定義元素
定義元素就是定義元素的 名字 和 內容模型 。
在 XML Schema 中,元素的 內容模型 由其 型別 定義,因此 XML 文件中例項元素的值必須符合模式中定義的型別。
型別包括簡單型別和複雜型別。
簡單型別的值不能包含元素或屬性。XML Schema 規範也包括預定義的簡單型別。 派生的簡單型別約束了基型別的值。
複雜型別可以產生在其他元素中巢狀元素的效果,或者為元素增加屬性。
1、簡單的、非巢狀的元素是簡單型別
不含屬性或其他元素的元素可以定義為簡單型別,無論是預定義的簡單型別還是使用者定義的簡單型別,如 預定義的簡單型別:string 、 integer 、 decimal 、 time ; 使用者定義的簡單型別:ProductCode 等等。
簡單型別定義
<element name='age' type='integer'/> <element name='price' type='ProductCode'/>
2、使用基型別來定義新的簡單型別,建立一個新的整數型別稱為myInteger,它的值範圍為10000到99999:
<xsd:simpleType name="myInteger"> <xsd:restriction base="xsd:integer"> <xsd:minInclusive value="10000"/> <xsd:maxInclusive value="99999"/> </xsd:restriction> </xsd:simpleType>
3、帶有屬性的元素必須是複雜型別。一個複雜元素型別:
<element name='price'> <complexType base='decimal' derivedBy='extension'> <attribute name='currency' type='string'/> </complexType> </element> <!-- In XML instance document, we can write: <price currency='US'>45.50</price> -->
在例子中,我們定義了一個 匿名型別,沒有明確地命名這個複雜型別。換句話說,沒有定義複雜型別 complexType 的 name 屬性。
4、嵌入其他元素的元素必須是複雜型別
<element name='Book' type='BookType'/> <complexType name='BookType'> <element name='Title' type='string'/> <element name='Author' type='string'/> </complexType>
5、用全域性簡單型別定義的複雜型別
<element name='Title' type='string'/> <element name='Author' type='string'/> <element name='Book' type='BookType'/> <complexType name='BookType'> <element ref='Title'/> <element ref='Author'/> </complexType>
在例子中, BookType 是全域性性的,可用於宣告其他元素。元素 Title 、 Author 和 Book 也是全域性範圍的。
元素 element 的 ref 屬性使您能夠引用前面宣告的元素。
6、隱藏 BookType 作為本地型別
<element name='Title' type='string'/> <element name='Author' type='string'/> <element name='Book'> <complexType> <element ref='Title'/> <element ref='Author'/> </complexType> </element>
7、表示元素型別的約束
<element name='Title' type='string'/> <element name='Author' type='string'/> <element name='Book'> <complexType> <element ref='Title' minOccurs='0'/> <element ref='Author' maxOccurs='2'/> </complexType> </element>
對於表示元素內容模型的約束,XML Schema 比 DTD 提供了更大的靈活性。
在最簡單的層次上,像在 DTD 中那樣,您可以把屬性和元素宣告關聯起來,指明能夠出現的給定元素集合序列:只能出現 1 次(1)、出現 0 次或多次(*)或者出現 1 次或多次(+)。
您還可以表示 XML Schema 中的其他約束,比方說使用 element 元素的 minOccurs 和 maxOccurs 屬性,以及 choice 、 group 和 all 元素。
在例子中, Book 中 Title 的出現是可選的(類似 DTD 的 '?')。
但是, 例子也說明 Book 元素中至少要有一個但不能超過兩個 Author 。
element 的 minOccurs 和 maxOccurs 屬性的預設值是 1。
元素 choice 只允許它的一個子女出現在例項中。
另外一個元素 all ,表示這樣的約束:組中的所有子元素可以同時出現一次,或者都不出現,它們可以按任意的順序出現。
8、指出必須為元素定義所有的型別
<xsd:element name='Title' type='string'/> <xsd:element name='Author' type='string'/> <xsd:element name='Book'> <xsd:complexType> <xsd:all> <xsd:element ref='Tile'/> <xsd:element ref='Author'/> </xsd:all> </xsd:complexType> </xsd:element>
例子表示 Title 和 Author 兩者必須同時出現(順序任意)在 Book 中,或者都不出現。這種約束很難在 DTD 中表示。