【转载】XML命名空间

.xml文件是很常见的配置文件类型,也经常会遇到,这篇文章以spring官方文档里面的一个.xml文件片段来讲解一下XML命名空间。

<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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean name="classic" class="com.example.ExampleBean">
 <property name="email" value="someone@somewhere.com"/>
 </bean>
 <bean name="p-namespace" class="com.example.ExampleBean"
 p:email="someone@somewhere.com"/>
</beans>

上面文件中和有xmlns的属性都跟XML命名空间有关,引入命名空间的作用就是为了避免名称冲突,这点应该不用说得太多。

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

这行代码的意思是“此.xml文件(此行代码所在的.xml文件)里面元素和属性的命名空间是‘http://www.springframework.org/schema/beans ’ ”,这个uri并不一定是可访问的实际资源,只是写成这种形式可以避免命名空间的重复,当然也可能就是可访问的资源。

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

这行代码的意思是“此.xml文件里面以xsi为前缀的元素和属性的命名空间是‘http://www.w3.org/2001/XMLSchema-instance ’ ”。

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

xsi:schemaLocation这个属性的命名空间就是"http://www.w3.org/2001/XMLSchema-instance",这个属性由两部分构成,以空格分隔。前一部分是此.xml文件里面元素和属性的命名空间,后一部分是一个URI,指向此.xml文件的XML Schema 文档,也就是规定此.xml文件里面的元素和属性结构的文件,标准XML解析器可以通过这个.xsd文件知道如何解析此.xml文件。

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

这行代码的意思是“此.xml文件里面以p为前缀的元素和属性的命名空间是‘http://www.springframework.org/schema/p ’ ”,例如,文件里面p:email这个属性的命名空间就是它。

作者:强力小磊哥原文地址:https://segmentfault.com/a/1190000023453161

%s 个评论

要回复文章请先登录注册