關於XML文檔的xmlns、xmlns:xsi和xsi:schemaLocation
摘要
相信很多人和我一樣,在編寫Spring或者Maven或者其他需要用到XML文檔的程序時,通常都是將這些XML文檔頭拷貝過來,並沒有理解其中元素(比如xmlns,xmlns:xsi,xsi:schemaLocation)的真正含義,不知道哪些元素是多餘的,也不知道爲什麼要加那些元素。
前言
先給大家看一個 Spring 容器的 xml 文檔:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ctx="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<ctx:component-scan base-package="vip.wulang"/>
</beans>
根元素 beans 先不說了,xmlns 全稱 XML NameSpace,譯爲"XML命名空間"。
爲什麼需要 xmlns 呢?
先看下面兩個例子:
<!-- 案例一 -->
<table>
<tr>
<td>Apple</td>
<td>Banana</td>
</tr>
</table>
<!-- 案例二 -->
<table>
<name>Coffee</name>
<width>20</width>
<length>40</length>
</table>
倘若這兩個同時要使用在一個 xml 中,XML 解析器無法辨別該遵循哪一個規範。那我們可能會想到加個類似於 html 中的 css,通過 id 或者 class 等來識別。在 xml 文件也是如此,不過不是叫 id,而是叫 xmlns,它的語法是:
xmlns:[Id]="[url]"
舉個例子:
<beans ... xmlns:ctx="http://www.springframework.org/schema/context" ...>
<ctx:component-scan base-package="vip.wulang"/>
</beans>
ctx 就是Id,http://www.springframework.org/schema/context 就是 url,其中用 id + XML命名空間內部元素,即可調用。當然不寫 Id,即默認:
<beans ... xmlns="http://www.springframework.org/schema/beans" ...>
<bean class="vip.wulang.config.WebMVCConfig" />
</beans>
xsi:schemaLocation有何作用?
xsi:schemaLocation 屬性其實是 NameSpace 爲 http://www.w3.org/2001/XMLSchema-instance 裏的 schemaLocation 屬性,正是因爲我們一開始聲明瞭:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
這裏才寫作 xsi:schemaLocation(當然一般都使用這個前綴)。它定義了 XML Namespace 和對應的 XSD(Xml Schema Definition)文檔的位置的關係。它的值由一個或多個 URI 引用對組成,兩個 URI 之間以空白符分隔(空格和換行均可)。第一個 URI 是定義的 XML Namespace 的值,第二個 URI 給出 Schema 文檔的位置,Schema 處理器將從這個位置讀取 Schema 文檔,該文檔的 targetNamespace 必須與第一個 URI 相匹配。例如:
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
這裏表示 Namespace 爲 http://www.springframework.org/schema/context 的Schema的位置爲 http://www.springframework.org/schema/context/spring-context.xsd 。這裏我們可以打開這個 Schema 的位置,下面是這個文檔的開始部分:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.springframework.org/schema/context"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tool="http://www.springframework.org/schema/tool"
targetNamespace="http://www.springframework.org/schema/context"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
</xsd:schema>
請注意 targetNamespace 的值必須於第一個 URI 匹配。
結束語
理解一個大概,對於後面如何書寫 xml 有了一個認知就行了。如果需要仔細研究請參考相關文章。