天天看点

XML(1)——shema约束之命名空间

一、xml的两种约束dtd和schema

摘自ibm官网一段话:“xml dtd(xml的文档类型定义)是近几年来xml技术领域所使用的最广泛的一种模式。但是由于xml dtd并不能完全满足xml自动化处理的要求,例如不能很好实现应用程序不同模间的相互协调,缺乏对文档结构、属性、数据类型等约束的足够描述等等,所以w3c于2001年5月正式推荐xml schema为xml 的标准模式。显然,w3c希望以xml schema来作为xml模式描述语言的主流,并逐渐代替xml dtd”。可见schema使用的越来越多,本文先阐述shema约束中非常重要的概念命名空间。

二、shema文件

student.xsd

<?xml version="1.0" encoding="utf-8"?>

<schema

xmlns="http://www.w3.org/2001/xmlschema" 

targetnamespace="http://www.example.org/student"

elementformdefault="qualified">

<element name="student">

<complextype>

<sequence>

<element name="num" type="int" />

<element name="name" type="string" />

<element name="birthday" type="date" />

</sequence>

</complextype>

</element>

</schema>

student.xsd就是一个shema文件,本身也是xml格式的,也要符合一定的约束。通过几个问题来理解xmlns和targetnamespace。

问题1如何保证shema文件唯一性:targetnamespace

因为在引用shema文件作为xml约束时,试想若有多个shema文件同名以哪一个约束为准呢?所以shema通过命名空间的概念来确保唯一性,targetnamespace属性就是指定这个xsd的命名空间的。通常使用url的形式作为targetnamespace的值来确保唯一性,而该url通常并不一定存在。

问题2如何引入shema规范:xmlns

xsd所有的标签和属性也必须符合schema规范,那element、complextype、sequence等标签的规范从何而来呢?

通过xmlns属性来指定shema约束。xmlns="http://www.w3.org/2001/xmlschema"就表示student.xsd默认不加前缀的标签和属性必须符合w3s定义的一个schema约束。若shema文件不是w3c组织定义的就需要指定shema文件的位置。下面xml引入student.xsd约束时有介绍。

问题3elementformdefault是什么意思

该属性是一个枚举值:qualified、unqualified。默认是unqualified表示只关联根标签student,而qualified表示关联所有标签和属性如num,name,birthday。

三、xml文件引入约束

方法1

student.xml

<student xmlns="http://www.example.org/student" 

xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"

xsi:schemalocation="http://www.example.org/student student.xsd">

<num>1000</num>

<name>xy</name>

<birthday>2000-01-01</birthday>

</student>

student.xml指定了xmlns="http://www.example.org/student"约束,就是自定义的student.xsd。但正如问题②所说shema文件不是w3c组织定义的就需要指定shema文件的位置。

问题4如何指定xsd位置:schemalocation

通过schemalocation指定shema文件位置。但schemalocation属性由http://www.w3.org/2001/xmlschema-instance约束,所以需要再通过xmlns引入这个约束。但一个标签中只允许一个不带前缀的xmlns标签,所以要给新的xmlns带一个前缀xsi,前缀名自定义。以下的例子很好的说明了前缀的用法:

<xy:student

xmlns:xy="http://www.example.org/student"

<xy:num>1000</xy:num>

<xy:name>xy</xy:name>

<xy:birthday>2000-01-01</xy:birthday>

</xy:student>

方法2

没有通过指定shema的命名空间而是xsd问位置来确定约束。

xmlns:xy="http://www.example.org/student" 

xsi:nonamespaceschemalocation="/studnet.xsd">

首段摘自:http://www.ibm.com/developerworks/cn/xml/x-sd/