關於XML Schema名稱空間中已經有xmlns卻還要targetnamespace的理解
最近在學習XML Schema,沒法很好的分清名稱空間的xmlns、targetnamespace的區別,為什麼在已經有全域性名稱空間xmlns和定義的名稱空間xmlns:prefix後還要加入一個targetnamespace。上StackoverFlow找到一些解釋,現在拿出來分享一下。
為什麼要用targetnamespace?
通常一個很小的xml文件不需要複雜的名稱空間來限定作用域。但是當文件複雜性越來越大,全的名稱空間規則很複雜,如果要通過XML Schema來建立和修改XML的內容限定的話,很多人會習慣性的在一個檔案中儲存所有的Schema。但是實際上一個良好的符合標準的規範應當是將文件分成很多個子Schema,這個過程可以叫做XML Schema Binding。名稱空間就是一個分割Schema的機制,子schema被包含在一個父schema中,這樣就提高了複用性,使得一個schema包可以用在很多的工程中。而且這樣能夠提高定義的可讀性,也使文件易於管理。
xmlns:prefix="http:/www.w3c.com" 這種形式是自定義prefix的方式來命名作用空間,屬於最小的作用域。
xmlns="http:/www.w3c.com" 這種形式是定義預設名稱空間,文件內所有的未做限定的元素都在這個名稱空間下。
targetnamespace就是收羅不同檔案的統一的一個域名。
形象地比喻來說就像一個Java工程裡,class檔案中通常會標明檔案歸屬的包import packagetargetnamespace類比於包的名字。
例:
常見的XML及其XML Schema樣式
XML:
<p:Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://localhost:8080/scribble/xml/Person" xmlns:v="http://localhost:8080/scribble/xml/Vehicle" xsi:schemaLocation=" http://localhost:8080/scribble/xml/Person http://localhost:8080/scribble/xml/person.xsd"> <name>John</name> <age>28</age> <height>59</height> <v:Vehicle> <color>Red</color> <wheels>4</wheels> <seats>2</seats> </v:Vehicle> </p:Person>
該XML沒有預設名稱空間,但是有xmlns:p和xmlns:v標識URI
Schema:
Person:
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://localhost:8080/scribble/xml/Person"
elementFormDefault="qualified"
xmlns:v="http://localhost:8080/scribble/xml/Vehicle">
<import
namespace="http://localhost:8080/scribble/xml/Vehicle"
schemaLocation="http://localhost:8080/scribble/xml/v.xsd"/>
<element name="Person">
<complexType>
<sequence>
<element name="name" form="unqualified" type="NCName"/>
<element name="age" form="unqualified" type="integer"/>
<element name="height" form="unqualified" type="integer"/>
<element ref="v:Vehicle"/>
</sequence>
</complexType>
</element>
</schema>
Vehicle:
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://localhost:8080/scribble/xml/Vehicle"
elementFormDefault="qualified">
<element name="Vehicle">
<complexType>
<sequence>
<element name="color" form="unqualified" type="NCName"/>
<element name="wheels" form="unqualified" type="integer"/>
<element name="seats" form="unqualified" type="integer"/>
</sequence>
</complexType>
</element>
</schema>
XML檔案受Person限制,Person檔案含有Vehicle限制。兩個Schema檔案的預設名稱空間都是:而targetNamespace被用作了例項XML的別名p和v。這裡targetNamespace作為例項檔案的名稱空間,與xml例項檔案中的schema檔案等宣告的名稱空間關係不大。targetNamespace就好像一個會議的名單,檔案中的名稱空間就像是一個人的姓名牌,只要姓名牌和名單對上了就能用。在這裡v的名稱空間級別最高,p的就要服從於v。http://www.w3.org/2001/XMLSchema
有了這樣的名稱空間的規則,這樣schema的複用性就能很好地體現。