分层 Schema
因为以往的设计方法很简单,它会导致内嵌设计变得深奥,使之难以可读并且当文件复杂的时候难以维护。另外一个不利的地方是,XML和DTD在结构上差别很大,给人和机器在想将DTD转换到XML Scheme的时候造成了很大的麻烦,甚至在两种技术上无法使用同一个设计指导。
第二种设计基于一个所有在实例文档中可用元素的目录,包括其中的每个元素,例如子元素和属性的列表。这种作用是通过使用元素参考和必须符合范围的参考的属性定义,实现了简单设计:
<?
xml version="1.0" encoding="UTF-8"
?>
< xs:schema xmlns:xs ="http://www.w3.org/2001/XMLSchema" >
<!-- definition of simple type elements -->
< xs:element name ="title" type ="xs:string" />
< xs:element name ="author" type ="xs:string" />
< xs:element name ="name" type ="xs:string" />
< xs:element name ="friend-of" type ="xs:string" />
< xs:element name ="since" type ="xs:date" />
< xs:element name ="qualification" type ="xs:string" />
<!-- definition of attributes -->
< xs:attribute name ="isbn" type ="xs:string" />
<!-- definition of complex type elements -->
< xs:element name ="character" >
< xs:complexType >
< xs:sequence >
< xs:element ref ="name" />
< xs:element ref ="friend-of" minOccurs ="0" maxOccurs ="unbounded" />
< xs:element ref ="since" />
< xs:element ref ="qualification" />
<!-- the simple type elements are referenced using
the "ref" attribute -->
<!-- the definition of the cardinality is done
when the elements are referenced -->
</ xs:sequence >
</ xs:complexType >
</ xs:element >
< xs:element name ="book" >
< xs:complexType >
< xs:sequence >
< xs:element ref ="title" />
< xs:element ref ="author" />
< xs:element ref ="character" minOccurs ="0" maxOccurs ="unbounded" />
</ xs:sequence >
< xs:attribute ref ="isbn" />
</ xs:complexType >
</ xs:element >
</ xs:schema >
< xs:schema xmlns:xs ="http://www.w3.org/2001/XMLSchema" >
<!-- definition of simple type elements -->
< xs:element name ="title" type ="xs:string" />
< xs:element name ="author" type ="xs:string" />
< xs:element name ="name" type ="xs:string" />
< xs:element name ="friend-of" type ="xs:string" />
< xs:element name ="since" type ="xs:date" />
< xs:element name ="qualification" type ="xs:string" />
<!-- definition of attributes -->
< xs:attribute name ="isbn" type ="xs:string" />
<!-- definition of complex type elements -->
< xs:element name ="character" >
< xs:complexType >
< xs:sequence >
< xs:element ref ="name" />
< xs:element ref ="friend-of" minOccurs ="0" maxOccurs ="unbounded" />
< xs:element ref ="since" />
< xs:element ref ="qualification" />
<!-- the simple type elements are referenced using
the "ref" attribute -->
<!-- the definition of the cardinality is done
when the elements are referenced -->
</ xs:sequence >
</ xs:complexType >
</ xs:element >
< xs:element name ="book" >
< xs:complexType >
< xs:sequence >
< xs:element ref ="title" />
< xs:element ref ="author" />
< xs:element ref ="character" minOccurs ="0" maxOccurs ="unbounded" />
</ xs:sequence >
< xs:attribute ref ="isbn" />
</ xs:complexType >
</ xs:element >
</ xs:schema >
使用元素或属性的引用某种程度上好克隆一个对象相似。元素或者属性首先被定义,然后在该文档的其他地方可以通过引用机制被复制,同样对象也可以被克隆。这两个元素(或属性)那么就是同一个类的两个实例。
下面的章节我们将讲述怎样定义“types”这种类,它允许我们复用元素定义。