xml_schema约束

schema介绍

schema符合xml的语法

一个xml中可以拥有多个schema,使用名称空间进行划分

dtd中有PCDATA一种数据类型,而schema有多种数据类型

schema语法复杂,schema目前不能替代dtd,但是最初的目的是为了替代dtd

schema的快速入门

<?xml version="1.0" encoding="UTF-8"?>
<schema 
	xmlns="http://www.w3.org/2001/XMLSchema" 
	targetNamespace="http://www.example.org/person" 
	elementFormDefault="qualified">
</schema>

schema本身是个xml文件,所以必须声明<?xml version="1.0" encoding="UTF-8"?>

xmlns:虽然schema实质是一个xml文件,但是它的后缀名为.xsd,也需要申明它是一个schema约束文件,它是一个固定值"http://www.w3.org/2001/XMLSchema"

targetNamespace:名称空间,这里是个随意值,一般用url表示,不与其它schema约束文件的名称空间相同即可,在xml文件中通过这个引入

elementFormDefault:详见1 详见2

注意:schema文件中的根元素必须是<schema></schema>

书写步骤:

1.判断xml文件中有多少个元素<element>

2.判断是复杂元素还是简单元素

复杂元素:<element><complexType><sequence></sequence></complexType></element>

简单元素(写在复杂元素里边):<element name=""></element>

<?xml version="1.0" encoding="gbk" standalone="no"?>
<person>
	<p1>
		<name>张三</name>
		<age>20</age>
	</p1>
	<p2>
		<name>李四</name>
		<age>100</age>
	</p2>
</person>
<?xml version="1.0" encoding="UTF-8"?>
<schema 
	xmlns="http://www.w3.org/2001/XMLSchema" 
	targetNamespace="http://www.example.org/person" 
	xmlns:tns="http://www.example.org/person" 
	elementFormDefault="qualified">
	<element name="person">
		<complexType>
			<sequence>
				<element name="p1">
					<complexType>
						<sequence>
							<element name="name"></element>	
							<element name="age"></element>
						</sequence>
					</complexType>
				</element>
				<element name="p2">
					<complexType>
						<sequence>
							<element name="name"></element>
							<element name="age"></element>
						</sequence>
					</complexType>
				</element>
			</sequence>
		</complexType>
	</element>
</schema>

在xml文件引入schema

在xml文件<person>标签中加入以下内容

xmlns:xsi:申明该xml文件是被约束文件

xmlns:引用xsd的空间名称

xsi:schemaLocation="空间名称 xsd文件名"

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.example.org/person"
	xsi:schemaLocation="http://www.example.org/person person.xsd">
	<p1>
		<name>张三</name>
		<age>20</age>
	</p1>
	<p2>
		<name>李四</name>
		<age>100</age>
	</p2>
</person>

schema的元素及属性

<sequence></sequence>:表示元素有序

<all></all>:表示相同元素只能出现一次

<choice></choice>:表示所有元素只能出现一个

maxOccurs="unbounded":表示元素出现没有限制

<any></any>:表示任意元素

属性标签(复杂元素):<attribute></attribute>

</attribute><!-- id:属性名称 type:数据类型 use:是否必须出现该属性 -->
<attribute name="id" type="int" use="optional">
		</complexType>

猜你喜欢

转载自blog.csdn.net/weixin_42061805/article/details/81627989