使用Schema验证XML文档

一个名为person.xml的文档:

<?xml version="1.0" encoding="UTF-8"?>
<person>
	<p>
		<name>张三</name>
		<age>30</age>
	</p>
	<p>
		<name>李四</name>
		<age>10</age>
	</p>
</person>

通过一个名为person.xsd的Schema文档对上边的person.xml文档进行约束

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.guo.tsu.com"
elementFormDefault="qualified">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
	<xs:element name="p" maxOccurs="unbounded">
	<xs:complexType>
	<xs:sequence>
		<xs:element name="name" type="xs:string"></xs:element>
		<xs:element name="age" type="xs:int"></xs:element>
	</xs:sequence>
	</xs:complexType>
	</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

其中:

  • xmlns:xs="http://www.w3.org/2001/XMLSchema",表示当前文档是一个约束文档
  • targetNamespace="http://www.guo.tsu.com",使用Schema约束文件,直接通过这个地址引入约束文件,可随便写,一般为一个url地址。
  • elementFormDefault="qualified",目标命名空间必须遵循Schema

对xml Schema的引用

 

<?xml version="1.0" encoding="UTF-8"?>
<person
xmlns="http://www.guo.tsu.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.guo.tsu.com person.xsd">
	<p>
		<name>张三</name>
		<age>30</age>
	</p>
	<p>
		<name>李四</name>
		<age>10</age>
	</p>
</person>

其中:

  • xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",表示当前文档是一个被约束文档
  • xmlns="http://www.guo.tsu.com",是约束文档里面的targetNamespace
  • xsi:schemaLocation="http://www.guo.tsu.com person.xsd",targetNamespace+空格+Schema文档的路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值