在定义XML Schema时,通常我们会定义一些命名空间,例如:
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.liulutu.com/students/" targetNamespace="http://www.liulutu.com/students/"> ... </schema>
(以下我的理解,错了别怪我)
其中:
- xmlns:定义了默认的命令空间,也就是在当前schema中元素的默认命名空间。例如"schema"元素,由于没有给出一个名称空间前缀,所以默认的命名空间就是由"xmlns"给出的值http://www.w3.org/2001/XMLSchema。
- targetNamespace:目标元素的命名空间。所谓的目标元素是指符合这份schema定义的xml文档里的元素,例如:
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.liulutu.com/students/" targetNamespace="http://www.liulutu.com/students/"> <element name="students"> <complexType> <sequence> <element name="student" type="tns:StudentType" maxOccurs="unbounded" /> </sequence> </complexType> </element> <simpleType name="SexType"> <restriction base="string"> <enumeration value="Male"></enumeration> <enumeration value="Female"></enumeration> </restriction> </simpleType> <complexType name="StudentType"> <attribute name="sex" type="tns:SexType"></attribute> <attribute name="name" type="string"></attribute> </complexType> </schema>
对应的一份可能的目标xml内容为:<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:students xmlns:ns2="http://www.liulutu.com/students/"> <student name="aaa" sex="Male"/> <student name="bbb" sex="Female"/> </ns2:students>
那个这个targetNamespace就是用来定义students和student元素的名称空间 - xmlns:tns:一份Xml schema里有时可能不止引用一个名称空间,因此就使用"xmlns:XXX"格式来定义一些其他的名称空间,然后引用些空间里的元素如下:"XXX:name"
要声明一个schema的地址,可以如下做:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3school.com.cn note.xsd"
其中schemaLocation的namespace需要是XMLSchema的名称空间,每个Location是一对值,其中前半部分代表这个schema的名称空间,后半部分值代码schema文件的路径