一个名为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文档的路径