.xml文件是很常見的配置文件類型,也經常會遇到,這篇文章以spring官方文檔裏面的一個.xml文件片段來講解一下XML命名空間。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="classic" class="com.example.ExampleBean">
<property name="email" value="[email protected]"/>
</bean>
<bean name="p-namespace" class="com.example.ExampleBean"
p:email="[email protected]"/>
</beans>
上面文件中和有xmlns的屬性都跟XML命名空間有關,引入命名空間的作用就是爲了避免名稱衝突,這點應該不用說得太多。
xmlns="http://www.springframework.org/schema/beans"
這行代碼的意思是“此.xml文件(此行代碼所在的.xml文件)裏面元素和屬性的命名空間是‘http://www.springframework.org/schema/beans ’ ”,這個uri並不一定是可訪問的實際資源,只是寫成這種形式可以避免命名空間的重複,當然也可能就是可訪問的資源。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
這行代碼的意思是“此.xml文件裏面以xsi爲前綴的元素和屬性的命名空間是‘http://www.w3.org/2001/XMLSchema-instance ’ ”。
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
xsi:schemaLocation這個屬性的命名空間就是"http://www.w3.org/2001/XMLSchema-instance",這個屬性由兩部分構成,以空格分隔。前一部分是此.xml文件裏面元素和屬性的命名空間,後一部分是一個URI,指向此.xml文件的XML Schema 文檔,也就是規定此.xml文件裏面的元素和屬性結構的文件,標準XML解析器可以通過這個.xsd文件知道如何解析此.xml文件。
xmlns:p="http://www.springframework.org/schema/p"
這行代碼的意思是“此.xml文件裏面以p爲前綴的元素和屬性的命名空間是‘http://www.springframework.org/schema/p ’ ”,例如,文件裏面p:email這個屬性的命名空間就是它。