关于XML文档的xmlns、xmlns:xsi和xsi:schemaLocation

关于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 有了一个认知就行了。如果需要仔细研究请参考相关文章。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章