關(guān)于xml文件 xsi:schemaLocation

相信很多人對(duì)xml 頭上一大堆得東西都是拿來(lái)主義,copy過(guò)來(lái)就行了,并不理解那是什么意思

先來(lái)一段

<?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的縮寫(xiě),可譯為“XML命名空間”

為什么需要xmlns?

因?yàn)閤ml文件有成千上萬(wàn),誰(shuí)也不能保證你的標(biāo)簽是獨(dú)一無(wú)二的,總是會(huì)沖突的,這時(shí)就需要xmlns了!

怎么使用xmlns 呢?

使用語(yǔ)法: xmlns:namespace-prefix="namespaceURI"。其中namespace-prefix為自定義前綴,只要在這個(gè)XML文檔中保證前綴不重復(fù)即可;namespaceURI是這個(gè)前綴對(duì)應(yīng)的XML Namespace的定義。例如:

xmlns:context="http://www.springframework.org/schema/context"

這里的<component-scan/>元素就來(lái)自別名為context的XML Namespace,也就是在http://www.springframework.org/schema/context中定義的。
其實(shí)我們完全可以將前綴定義為abc:

xmlns:abc="http://www.springframework.org/schema/context"

好了,看到這里,你也許會(huì)問(wèn) 那 xmlns 和xmlns:context 有什么區(qū)別呢?

xmlns 沒(méi)有帶別名,就是表示那是默認(rèn)的,如

<bean id="xxx" class="xxx.xxx.xxx.Xxx">
<property name="xxx" value="xxxx"/>
</bean>

這里的bean 屬性就出自這個(gè)默認(rèn)命名空間

xsi:schemaLocation 是干嘛的?

看到這里也許你已經(jīng)知道了它是干嘛的了
schemaLocation不就是 xsi 命名空間的一個(gè)屬性嗎,如果之前我們把
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 的別名改成
xmlns:sb="http://www.w3.org/2001/XMLSchema-instance"

這里其實(shí)就變成 sb:schemaLocation,這里講一下這個(gè)屬性是干嘛的,這個(gè)屬性的值由一個(gè)或多個(gè)URI引用對(duì)組成,兩個(gè)URI之間以空白符分隔(空格和換行均可)
它定義了XML Namespace和對(duì)應(yīng)的 XSD(Xml Schema Definition)文檔的位置的關(guān)系,意思就是 這個(gè)命名空間對(duì)應(yīng)的具體模板是哪個(gè)

例如我們打開(kāi) http://www.springframework.org/schema/mvc/ 這個(gè) 命名空間,可以看到有很多選擇

Paste_Image.png

xsi:schemaLocation 這個(gè)屬性就是跟他說(shuō)我要選擇哪一個(gè)

博客原文地址戳這里

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容