关于命名空间

命名空间的作用是为了避免元素命名冲突

 

命名冲突

在XML中,元素名称是自定义的,当两个不同的XML树在同一个文档中使用相同的元素名时,就会发生命名冲突,如下:
它们都使用到了

,XML解析器无法确定如何处理这类冲突


<table>
    <tr>
        <td>Applestd>
        <td>Bananastd>
    tr>
table>



<table>
    <name>African Coffee Tablename>
        <width>80width>
    <length>120length>
table>

 

前缀

在XML中的命名冲突可以通过使用名称前缀从而容易地避免。如下:


<h:table>
    <h:tr>
        <h:td>Applesh:td>
        <h:td>Bananash:td>
    h:tr>
h:table>

<f:table>
    <f:name>African Coffee Tablef:name>
    <f:width>80f:width>
    <f:length>120f:length>
f:table>

 

命名空间

当在XML中使用前缀时,必须定义命名空间,使得该命名空间与前缀相关联
命名空间是在元素的开始标签的 xmlns 属性中定义的

命名空间声明的语法:xmlns:前缀="URI"。

在下面实例中,

标签的xmlns属性定义了 h: 和 f: 前缀的合格命名空间


<root>

    <h:table xmlns:h="http://www.w3.org/TR/html4/">
        <h:tr>
            <h:td>Applesh:td>
            <h:td>Bananash:td>
        h:tr>
    h:table>

    <f:table xmlns:f="http://www.w3cschool.cc/furniture">
        <f:name>African Coffee Tablef:name>
        <f:width>80f:width>
        <f:length>120f:length>
    f:table>

root>



<root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3cschool.cc/furniture">

    <h:table>
        <h:tr>
            <h:td>Applesh:td>
            <h:td>Bananash:td>
        h:tr>
    h:table>

    <f:table>
        <f:name>African Coffee Tablef:name>
        <f:width>80f:width>
        <f:length>120f:length>
    f:table>

root>

注意:
  命名空间URI不会被解析器用于查找信息。
  其目的是赋予命名空间一个惟一的名称
  但很多公司常常会作为指针来使用命名空间指向实际存在的网页,这个网页包含关于命名空间的信息

 

你可能感兴趣的:(关于命名空间)