Schema是定义XML文件内容结构的一种方法,一旦一个XML文件指定了Schema文件,其文件内容结构就必须符合Schema的定义。下面通过一个例子来讲解Schema的用法。
文件:1.xml
<?xml version="1.0" encoding="UTF-8"?>
<person:person xmlns:person="http://www.xxx.com/person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xxx.com/person file:///E:/XML/1.xsd">
<name>
<first>Chan</first>
<last>Eason</last>
</name>
<sex>男</sex>
<age>39</age>
</person:person>
文件:1.xsd
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.xxx.com/person"> <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="name"> <xs:complexType> <xs:sequence> <xs:element name="first" type="xs:string"></xs:element> <xs:element name="last" type="xs:string"></xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="sex" type="xs:string"></xs:element> <xs:element name="age" type="xs:integer"></xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
其中1.xsd是schema文件,1.xml是xml文件,1.xml使用1.xsd文件中所定义的内容格式。首先解析1.xml,容易看出,1.xml文件描述了一个人的名字、性别和年龄,其中名字又分为姓和名。其中person:person表示根元素,第一个person是名称空间,即
所定义。xmlns:person="http://www.xxx.com/person"
这句代码所表示的意思是名称空间xsi,其值是http://www.w3.org/2001/XMLSchema-instance,这其中包括很多预定义的东西,比如后面要用到的schemalocation。xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
这句代码表示的是所要使用的schema文件在file:///E:/XML/1.xsd,而http://www.xxx.com/person表示的是名称空间。xsi:schemaLocation="http://www.xxx.com/person file:///E:/XML/1.xsd"
下面解析1.xsd
其中xs代表名称空间,指向http://www.w3.org/2001/XMLSchema,这其中包含一些预定义的数据类型,比如string,integer等。targetNamespace表明该xsd文件所使用的名称空间,其值必须和xml文件中的schemalocation保持一致。<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.xxx.com/person">
表明xml中需要一个<person>元素<xs:element name="person">
表明<person>是一个复杂类型的元素<xs:complexType>
<xs:sequence>
表明<person>元素下的子元素是顺序排列的,依次有:<name>,<sex>,<age>,其中<name>是复杂类型元素,包含<first>和<last>。
另外想要验证XML文件是否复合schema定义不能使用浏览器,必须要使用XML解析器,推荐XMLSPY。