xmlns, xmlns:xsi, xsi:schemaLocation 解釋
我們在寫 xml 文件時,尤其是 spring 、mybatis 的配置文件時,經常會用到上 xmlns、xmlns:xsi、xsi:schemaLocation 等元素,但多數時候大家都是直接拷貝,並未真正理解這三個元素的具體含義。
今天整理出來,權當備忘。
請看下面一段 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="bean" class="com.feshfans.Bean"></bean>
</beans>
xmlns
xmlns 的全稱為 xml namespace,即 xml 命名空間,這個很好理解,和 java 中 package 和 c# 中 namespace 的概念基本一致,起的作用也基本一致:區分重復元素
xmlns 格式定義如下:
xmlns[:name] = "uri"
默認命名空間
name 可以忽略不填,即為默認命名空間,如:
xmlns="http://www.springframework.org/schema/beans"
表現效果則為命名空間中的元素可以不加前輟,在此 xml 中直接使用,如上面的
<bean id="bean" class="com.feshfans.Bean"></bean> // bean 元素可以直接使用
自定義命名空間
我們也可以自定義命名空間的名稱,如:
xmlns:context = "http://www.springframework.org/schema/context" // context 名稱可以隨便起,如 abc
表現效果為,我們在 xml 文件中使用此命名空間下的元素時,必須加上 context 前輟,如:
<context:component-scan base-package="com.feshfans"></context:component-scan>
為什么?
假如 xml 沒有命名空間,spring 定義了 bean 元素,mybatis 也定義了 bean 元素,那么我們使用的是哪個 bean 元素呢?顯示易見, xmlns 解決了元素沖突的問題
xmlns:xsi
這本質就是聲明一個名為 xsi 的命名空間,其值為一個標准的命名空間
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
此命名空間還定義了 xsi:type, xsi:nil, xsi:schemaLocation 等屬性
雖然 xsi 也可以隨意用別的名稱替換,但不建議這樣做。xsi 已經是通用的寫法, 是 xml schema instance 的縮寫,可以看成是固定寫法。
xsi:schemaLocation
此為 xsi 命名空間中定義的一個屬性,用於通知 xml 處理器 xml 文檔與 xsd 文件的關聯關系。
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
這里需要注意的是:命名空間和 命名空間的 xsd (xml schema defination,定義了命名空間下元素的寫法) 必須成對出現,中間用空格分分隔;可以填寫多個對應關系。
這也是一個通用的寫法,可以理解為固定寫法。
其它
其實,命名空間與其對應的 xsd 文件我們在 jar 中一般都是可以發現的,以 spring-beans.jar 為例:
在 META-INF 目錄下,spring.tooling 文件中可以找到命名空間的值,在 spring.schemas 文件中可以找到 xsd 文件的值,同時此文件中也定義了離線 xsd 文件的位置。