天天看點

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/