zoukankan      html  css  js  c++  java
  • xmlns, xmlns:xsi, xsi:schemaLocation 解释

    xmlns, xmlns:xsi, xsi:schemaLocation 解释

    我们在写 xml 文件时,尤其是 spring 、mybatis 的配置文件时,经常会用到上 xmlns、xmlns:xsi、xsi:schemaLocation 等元素,但多数时候大家都是直接拷贝,并未真正理解这三个元素的具体含义。

    今天整理出来,权当备忘。

    请看下面一段 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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
    
        <bean id="bean" class="com.feshfans.Bean"></bean>
    </beans>
    

    xmlns

    xmlns 的全称为 xml namespace,即 xml 命名空间,这个很好理解,和 java 中 package 和 c# 中 namespace 的概念基本一致,起的作用也基本一致:区分重复元素

    xmlns 格式定义如下:
    xmlns[:name] = "uri"

    默认命名空间

    name 可以忽略不填,即为默认命名空间,如:

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

    表现效果则为命名空间中的元素可以不加前辍,在此 xml 中直接使用,如上面的

    <bean id="bean" class="com.feshfans.Bean"></bean>   // bean 元素可以直接使用
    自定义命名空间

    我们也可以自定义命名空间的名称,如:

    xmlns:context = "http://www.springframework.org/schema/context"  // context 名称可以随便起,如 abc

    表现效果为,我们在 xml 文件中使用此命名空间下的元素时,必须加上 context 前辍,如:

    <context:component-scan base-package="com.feshfans"></context:component-scan>
    为什么?

    假如 xml 没有命名空间,spring 定义了 bean 元素,mybatis 也定义了 bean 元素,那么我们使用的是哪个 bean 元素呢?显示易见, xmlns 解决了元素冲突的问题

    xmlns:xsi

    这本质就是声明一个名为 xsi 的命名空间,其值为一个标准的命名空间

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    此命名空间还定义了 xsi:type, xsi:nil, xsi:schemaLocation 等属性

    虽然 xsi 也可以随意用别的名称替换,但不建议这样做。xsi 已经是通用的写法, 是 xml schema instance 的缩写,可以看成是固定写法。

    xsi:schemaLocation

    此为 xsi 命名空间中定义的一个属性,用于通知 xml 处理器 xml 文档与 xsd 文件的关联关系。

    xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    这里需要注意的是:命名空间和 命名空间的 xsd (xml schema defination,定义了命名空间下元素的写法) 必须成对出现,中间用空格分分隔;可以填写多个对应关系。

    这也是一个通用的写法,可以理解为固定写法。

    其它

    其实,命名空间与其对应的 xsd 文件我们在 jar 中一般都是可以发现的,以 spring-beans.jar 为例:

    在 META-INF 目录下,spring.tooling 文件中可以找到命名空间的值,在 spring.schemas 文件中可以找到 xsd 文件的值,同时此文件中也定义了离线 xsd 文件的位置。

  • 相关阅读:
    Struts2+Spring3+Mybatis3开发环境搭建
    spring+struts2+mybatis
    【LeetCode】Populating Next Right Pointers in Each Node
    【LeetCode】Remove Duplicates from Sorted Array
    【LeetCode】Remove Duplicates from Sorted Array II
    【LeetCode】Binary Tree Inorder Traversal
    【LeetCode】Merge Two Sorted Lists
    【LeetCode】Reverse Integer
    【LeetCode】Same Tree
    【LeetCode】Maximum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/feshfans/p/11154765.html
Copyright © 2011-2022 走看看