XML Schema 是基于 XML 的 DTD 替代者。
(了解DTD:http://blog.csdn.net/qfs_v/archive/2008/05/26/2482023.aspx)
XML Schema 描述 XML 文档的结构。
XSD--> XML Schema Definition
XML Schema的作用:
- 定义可出现在文档中的元素
- 定义可出现在文档中的属性
- 定义哪个元素是子元素
- 定义子元素的次序
- 定义子元素的数目
- 定义元素是否为空,或者是否可包含文本
- 定义元素和属性的数据类型
- 定义元素和属性的默认值以及固定值
XML Schema 支持数据类型
XML Schema 最重要的能力之一就是对数据类型的支持。
简单的示例:把下面的note.XML文档转化成xsd
<?xml version="1.0"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
note.xsd
<?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>
代码解释:
下面的片断:
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 定义的元素 (note, to, from, heading, body) 来自命名空间: "http://www.w3school.com.cn"。
这个片断:
xmlns="http://www.w3school.com.cn"
指出默认的命名空间是 "http://www.w3school.com.cn"。
这个片断:
elementFormDefault="qualified"
指出任何 XML 实例文档所使用的且在此 schema 中声明过的元素必须被命名空间限定。
对 XML Schema 的引用
<?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>
代码解释:
下面的片断:
xmlns="http://www.w3school.com.cn"
规定了默认命名空间的声明。此声明会告知 schema 验证器,在此 XML 文档中使用的所有元素都被声明于 "http://www.w3school.com.cn" 这个命名空间。
一旦您拥有了可用的 XML Schema 实例命名空间:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
您就可以使用 schemaLocation 属性了。此属性有两个值。第一个值是需要使用的命名空间。第二个值是供命名空间使用的 XML schema 的位置:
xsi:schemaLocation="http://www.w3school.com.cn note.xsd"