原文連接:https://www.jianshu.com/p/7f4cbcd9f09f
------------------------------------------------------
相信很多人對xml 頭上一大堆得東西都是拿來主義,copy過來就行了,并不理解那是什么意思
先來一段
<?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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><context:component-scan base-package="com.pikaq"/><bean id="xxx" class="xxx.xxx.xxx.Xxx"><property name="xxx" value="xxxx"/>
</bean>
</beans>
首先看到的就是 xmlns, xmlnsXML 是Namespace的縮寫,可譯為“XML命名空間”
為什么需要xmlns?
因為xml文件有成千上萬,誰也不能保證你的標簽是獨一無二的,總是會沖突的,這時就需要xmlns了!
怎么使用xmlns 呢?
使用語法: xmlns:namespace-prefix="namespaceURI"。其中namespace-prefix為自定義前綴,只要在這個XML文檔中保證前綴不重復即可;namespaceURI是這個前綴對應的XML Namespace的定義。例如:
xmlns:context="http://www.springframework.org/schema/context"
這里的<component-scan/>元素就來自別名為context的XML Namespace,也就是在http://www.springframework.org/schema/context中定義的。
其實我們完全可以將前綴定義為abc:
xmlns:abc="http://www.springframework.org/schema/context"
好了,看到這里,你也許會問 那 xmlns 和xmlns:context 有什么區別呢?
xmlns 沒有帶別名,就是表示那是默認的,如
<bean id="xxx" class="xxx.xxx.xxx.Xxx">
<property name="xxx" value="xxxx"/>
</bean>
這里的bean 屬性就出自這個默認命名空間
xsi:schemaLocation 是干嘛的?
看到這里也許你已經知道了它是干嘛的了
schemaLocation不就是 xsi 命名空間的一個屬性嗎,如果之前我們把
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 的別名改成
xmlns:sb="http://www.w3.org/2001/XMLSchema-instance"
這里其實就變成 sb:schemaLocation,這里講一下這個屬性是干嘛的,這個屬性的值由一個或多個URI引用對組成,兩個URI之間以空白符分隔(空格和換行均可)
它定義了XML Namespace和對應的 XSD(Xml Schema Definition)文檔的位置的關系,意思就是 這個命名空間對應的具體模板是哪個
例如我們打開 http://www.springframework.org/schema/mvc/ 這個 命名空間,可以看到有很多選擇