XML学习之Schema

      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"
所定义。

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
这句代码所表示的意思是名称空间xsi,其值是http://www.w3.org/2001/XMLSchema-instance,这其中包括很多预定义的东西,比如后面要用到的schemalocation。
xsi:schemaLocation="http://www.xxx.com/person file:///E:/XML/1.xsd"
这句代码表示的是所要使用的schema文件在file:///E:/XML/1.xsd,而http://www.xxx.com/person表示的是名称空间。

下面解析1.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.xxx.com/person">
其中xs代表名称空间,指向http://www.w3.org/2001/XMLSchema,这其中包含一些预定义的数据类型,比如string,integer等。targetNamespace表明该xsd文件所使用的名称空间,其值必须和xml文件中的schemalocation保持一致。

<xs:element name="person">
表明xml中需要一个<person>元素

<xs:complexType>
表明<person>是一个复杂类型的元素

<xs:sequence>

表明<person>元素下的子元素是顺序排列的,依次有:<name>,<sex>,<age>,其中<name>是复杂类型元素,包含<first>和<last>。

另外想要验证XML文件是否复合schema定义不能使用浏览器,必须要使用XML解析器,推荐XMLSPY。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值