XML Schema初探

Schema

 

什么是Schema

  Schema(模式) :其作用与DTD一样,也是用于验证XML文档的有效性,只不过它提供了比DTD更强大的功能和更细粒度的数据类型。

  另外,Schema可以自定义数据类型。

  Schema也是一个XML文件,而DTD则不是。

     

 

 

 

 

为何要Schema

 

Schema文档结构

 

  所有的Schema文档,其根元素必须叫schema。

  schema可以包含属性,比如:

 

<?xml version="1.0"?>
 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3school.com.cn"
xmlns="http://www.w3school.com.cn"
elementFormDefault="qualified">

...
...
</xs:schema>

 

  第一个xmlns后面的名字可以自由定义,一般是xsxsd,但是地址不可以改,是一定的:

xmlns:xs="http://www.w3.org/2001/XMLSchema"

  显示 schema 中用到的元素和数据类型来自命名空间 "http://www.w3.org/2001/XMLSchema"。

  同时它还规定了来自命名空间 "http://www.w3.org/2001/XMLSchema" 的元素和数据类型应该使用前缀 xs。

 

targetNamespace="http://www.w3school.com.cn" 

  显示被此 schema 定义的元素 (自定义的element,即XML中的标签) 来自命名空间: "http://www.w3school.com.cn"。

 

xmlns="http://www.w3school.com.cn" 

  指出默认的命名空间是 "http://www.w3school.com.cn"。

 

elementFormDefault="qualified" 

  指出任何 XML 实例文档所使用的且在此 schema 中声明过的元素必须被命名空间限定。

 

一个Schema的例子

  下面这个例子是一个名为 "note.xsd" 的 XML Schema 文件:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3school.com.cn"
xmlns="http://www.w3school.com.cn"
elementFormDefault="qualified">

<xs:element name="note">
    <xs:complexType>
      <xs:sequence>
    <xs:element name="to" type="xs:string"/>
    <xs:element name="from" type="xs:string"/>
    <xs:element name="heading" type="xs:string"/>
    <xs:element name="body" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>

  

  XML文档加入对其的引用:

<?xml version="1.0"?>
<note
xmlns="http://www.w3school.com.cn"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3school.com.cn note.xsd">

<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

  

  顺带介绍,如果上面的文档不用Schema,而是用DTD定义将会是这样:

<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

 

 

Schema的数据类型

简单类型

  一.内置的数据类型(built-in data types)

  内置的数据类型又分为两种:

  1.基本的数据类型

  2.扩展的数据类型

  二.用户自定义数据类型(通过simpleType定义)

复杂类型(通过complexType定义)

 

 

 

Schema元素

  

  关于元素的详细说明可以参见 XML Schema参考手册:

  http://www.w3school.com.cn/schema/schema_elements_ref.asp

 

 

 

参考资料

  W3school XML Schema:

  http://www.w3school.com.cn/schema/schema_intro.asp

  http://www.w3school.com.cn/schema/schema_schema.asp

  圣思园张龙老师视频教程。

  XML工具软件:XMLSpy。

posted @ 2013-06-01 16:45  圣骑士wind  阅读(975)  评论(0编辑  收藏  举报