在编写xml schema文档时,可以指定该模式文档是为哪一个命名空间声明和定义组件,这个命名空间成为目标名称空间。目标名称空间使用schema元素的targetNamespace属性来指定。需要注意的是,只有模式文档中的全局元素和全局属性才属于目标命名空间。以下是两个例子:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.sunxin.org/book" xmlns="http://www.sunxin.org/book">
<xs:element name="book" type="booktype"/>
<xs:complexType name="booktype">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
</xs:sequence>
<xs:attribute name="isbn" type="xs:token"/>
</xs:complexType>
</xs:schema>
示例1:使用了默认命名空间
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.sunxin.org/book" xmlns:bk="http://www.sunxin.org/book">
<xs:element name="book" type="bk:booktype"/>
<xs:complexType name="booktype">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
</xs:sequence>
<xs:attribute name="isbn" type="xs:token"/>
</xs:complexType>
</xs:schema>
示例2:没有使用默认命名空间
在模式文档中,需要指明类型所属的命名空间。类型booktype属于目标命名空间,当没有使用默认方式时,需要再其前面加上前缀。
模式文档中的局部元素title和author没有被目标命名空间限定(即局部元素不属于目标命名空间),如果要限定可以使用elementFormDefault来设置。elementFormDefault的值有两个,分别是qualified和unqualified。或者在节点元素后面加上form,其值分别是qualified和unqualified。如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.sunxin.org/book" xmlns="http://www.sunxin.org/book" elementFormDefault="unqualified">
<xs:element name="book" type="booktype"/>
<xs:complexType name="booktype">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
</xs:sequence>
<xs:attribute name="isbn" type="xs:token"/>
</xs:complexType>
</xs:schema>
示例3:使用elementFormDefault
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.sunxin.org/book" xmlns:bk="http://www.sunxin.org/book">
<xs:element name="book" type="bk:booktype"/>
<xs:complexType name="booktype">
<xs:sequence>
<xs:element name="title" type="xs:string" form="qualified"/>
<xs:element name="author" type="xs:string" form="unqualified"/>
</xs:sequence>
<xs:attribute name="isbn" type="xs:token"/>
</xs:complexType>
</xs:schema>
示例4:使用From
当设置为qualified时,局部元素必须是属于目标命名空间,否则,局部元素不能属于目标命名空间。(注意:当xml文档的默认命名空间就是目标命名空间时,如果局部元素不属于目标命名空间,可以在局部元素后面加上 xmlns=“”,来指定局部元素不属于任何命名空间)。
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.sunxin.org/book" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sunxin.org/book xs1.xml">
<title xmlns="">语文</title>
<author xmlns="">编辑社</author>
</book>