跟我学XML Schema(转)[5]

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 miki52777 的 blog

跟我学xml schema(10):定义属性

最后,我们再来讲讲元素的属性如何在schema文档中定义。

比如上面的order.xml实例文档中:

<order>
  <orderitem id="7-5058-3496-7" />
</order>

对此,我们在schema文档中采用一个attribute来定义:

order.xsd
---------
<xsd:element name="orderitem">
  <xsd:complextype>
    <xsd:sequence>  ←空元素
    </xsd:sequence>  
    
    <!--定义该元素属性-->
    <xsd:attribute name="id" type="xsd:string"/>
  </xsd:complextype>
</xsd:element>

那么,实例文档中该属性值是必须的还是可有可无的呢?我们可以这样限制:

<xsd:attribute name="id" type="idtype" use="required"/>

这里我们讲id属性类型作为一种自定义数据类型idtype。
而且,用attribute元素的use属性来定义是否是必须的属性。
required是必须值,optional是可选值,prohibited是无属性值。


那么对于属性的缺省值,我们怎么定义呢?
比如:
<order>
  <orderitem id="4-8443-1780-6" quantity="3"/>
</order>

我们还可以用attribute元素的另一个属性default来定义:
<xsd:attribute name="quantity" type="xsd:integer" default="1"/>

所以,我们可以重新写出一个schema文档:

order2.xsd
--------------
<xsd:element name="orderitem">
  <xsd:complextype>
    <xsd:sequence></xsd:sequence>
    <xsd:attribute name="id" type="idtype" use="required"/>
    <xsd:attribute name="quantity" type="xsd:integer" default="1"/>
  </xsd:complextype>
</xsd:element>

上面的属性我们定义我们还可以采用属性组的办法来重新改写schema文档。

order3.xsd
----------------
1:    <xsd:element name="orderitem">
2:      <xsd:complextype>
3:        <xsd:sequence></xsd:sequence>
4:        <xsd:attributegroup ref="orderitemattributes"/>
5:      </xsd:complextype>
6:    </xsd:element>
7:
8:    <xsd:attributegroup name="orderitemattributes">
9:      <xsd:attribute name="id" type="idtype" use="required"/>
10:      <xsd:attribute name="quantity" type="xsd:integer" default="1"/>
11:    </xsd:attributegroup>

这个属性组就不详细解释了,不过,大家一看就清楚了吧。

最后,我们写一个完整的订书order.xml的schema文档。
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></xsd:sequence>
15:        <xsd:attributegroup ref="orderitemattributes"/>
16:      </xsd:complextype>
17:    </xsd:element>
18:
19:    <xsd:attributegroup name="orderitemattributes">
20:      <xsd:attribute name="id" type="idtype" use="required"/>
21:      <xsd:attribute name="quantity" type="xsd:integer" default="1"/>
22:    </xsd:attributegroup>
23:
24:    <xsd:simpletype name="idtype">
25:      <xsd:restriction base="xsd:string">
26:        <xsd:pattern value="\d{1}-\d{4}-\d{4}-\d{1}"/>
27:      </xsd:restriction>
28:    </xsd:simpletype>
29:
30:  </xsd:schema>


本文关键:跟我学XML Schema(转)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top