</order>
这时书写schema文档还需要使用choice元素。
order2.xsd
-------------------------
1:<?xml version="1.0"?>
2:<xsd:schema xmlns:xsd="http://www.w3.org/2001/xmlschema">
3:
4: <xsd:element name="order">
5: <xsd:complextype>
6: <xsd:sequence>
7: <xsd:element ref="orderitem" maxoccurs="10" />
8: </xsd:sequence>
9: </xsd:complextype>
10: </xsd:element>
11:
12: <xsd:element name="orderitem">
13: <xsd:complextype>
14: <xsd:choice>
15: <xsd:element name="name" type="xsd:string"/>
16: <xsd:element name="id" type="xsd:string"/>
17: </xsd:choice>
18: </xsd:complextype>
19: </xsd:element>
20:
21:</xsd:schema>
跟我学xml schema(7):稍微更复杂的可选项子元素
再稍微修改一下订书数据的实例文档:
order3.xml
-----------------
<order>
<orderitem>
<name>accounting book</name>
<quantity>2</quantity>
</orderitem>
<orderitem>
<id>7-5058-3496-7</id>
</orderitem>
</order>
这里假定<quantity>值为1时,缺省。
如何修改schema文档呢?
order3.xsd
-----------------
1:<?xml version="1.0"?>
2:<xsd:schema xmlns:xsd="http://www.w3.org/2001/xmlschema">
3:
4: <xsd:element name="order">
5: <xsd:complextype>
6: <xsd:sequence>
7: <xsd:element ref="orderitem" maxoccurs="10"/>
8: </xsd:sequence>
9: </xsd:complextype>
10: </xsd:element>
11:
12: <xsd:element name="orderitem">
13: <xsd:complextype>
14: <xsd:sequence>
15: <xsd:choice>
16: <xsd:element name="name" type="xsd:string"/>
17: <xsd:element name="id" type="xsd:string"/>
18: </xsd:choice>
19: <xsd:element name="quantity" type="xsd:string" minoccurs="0"/>
20: </xsd:sequence>
21: </xsd:complextype>
22: </xsd:element>
23:
24:</xsd:schema>
19行中的quantity最少出现值为0,也就是可以有,也可以没有。
当然,也可以直接在<choice>元素中,包含quantity,然后定义它的minoccurs。
跟我学xml schema(8):内置简单类型
内建于xml schema的简单类型有44种。他们在xml schema推荐标准的第二部分中公布,下面这是一张内置类型的层次结构图:
http://www.w3.org/tr/2001/pr-xmlschema-2-20010330/type-hierarchy.jpg
跟我学xml schema(9):自定义简单类型
如果内置简单类型的44种还不能满足要求,怎么办呢?下面学习自定义简单类型。(xml的扩展性充分体现在这里)
例如这个实例文档:
order4.xml
-----------------
<order>
<orderitem>
<id>7-5058-3496-7</id>
<quantity>5</quantity>
</orderitem>
</order>
id是一个标准的isbn编码,我们怎么定义这个isbn编码呢?
<xsd:simpletype name="idtype">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{1}-\d{4}-\d{4}-\d{1}"/>
</xsd:restriction>
</xsd:simpletype>
idtype是一个自定义的简单类型。
我们对它做了限制:
<xsd:restriction base="xsd:string">代表它是基于一个字符串类型。再用pattern元素来描述该字符串的形式。
value="\d{1}-\d{4}-\d{4}-\d{1}"这是一个正则表达式,关于正则表达式,以后再介绍。嘻嘻!
利用这个自定义的简单类型,我们可以重新写schema文档:
order4.xsd
---------------
1:<?xml version="1.0"?>