# XML 文档 # xmlns: 和 xsi: 的作用

717 阅读1分钟

xmlns 命名空间

命名空间的主要作用是预防歧义

<table>
    <tr>
        <th></th>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>

<table>
    <name></name>
    <id></id>
</table>
  • 同一文档中存在同名标签,但是表达的意思不同,无法区分各自的作用
<html:table>
    <tr>
        <th></th>
    </tr>
    <tr>
        <td></td>
    </tr>
</html:table>

<xml:table>
    <name></name>
    <id></id>
</xml:table>
  • 各自加上命名空间后,就可以明确区分出它们不同,再根据各自的定义进行解释

默认命名空间是 beans

<?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-3.0.xsd">
      <bean id="xx" class=""/>
</beans>
  • <beans xmlns= 表示当前文档默认的命名空间是 beans
  • xmlns:xsi 定义一个叫 xsi命名空间,等号后面的值一般是指向介绍这个命名空间的网页,需保证唯一性,但不一定要求能访问
  • xsi:schemaLocation 表示命名空间的 xsd (xml文档结构定义)文件的所在位置,用于对指定命名空间的xml元素进行检验,格式是 xsi:schemaLocation = "键 值" ,注意中间有空格,如例子中 http://www.springframework.org/schema/beans 用命名空间表示键,http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 是它的值

多个命名空间

<?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:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.0.xsd"
      >
      <bean id="xxx" class=""/>
      <context:component-scan >
          <base-package>com.demo.base</base-package>
          <annotation-config>true</annotation-config>
      </context:component-scan>
</beans>
  • xmlns:context 加入表示上下文的命名空间
  • xsi:schemaLocation 中指出了,http://www.springframework.org/schema/context 命名空间的定义文档(xsd)在 http://www.springframework.org/schema/context/spring-context-4.0.xsd
  • <context:component-scan>context 表示命名空间,component-scan 表示该命名空间中的标签啊
    • 因为在该例子中,默认命名空间是 beans , 使用其它命名空间的标签需要显式声明使用