| 文章首页 |
|---|
| W3C官方XML命名空间介绍中文版 |
| 1 动机和摘要 |
| 2 声明命名空间 |
| 3 XML的合法名 |
| 4 使用合法名 |
| 5 命名空间在元素和属性中的运用 |
| 6 文件的一致 |
| 附录 |
页6 共8页
5.1 命名空间的范围
命名空间声明适用于声明它的元素和该元素内容中所有的元素,除非被其它具有同样 NSAttName 的命名空间声明所覆盖:<?xml version="1.0"?>一个元素可有多个命名空间前缀声明作为属性,例如:
<!-- 所有在这里的元素都明确地属於HTML的命名空间-->
<html:html xmlns:html='http://www.w3.org/TR/REC-html40'>
<html:head><html:title>Frobnostication</html:title></html:head>
<html:body><html:p>Moved to
<html:a href='http://frob.com'>here.</html:a></html:p></html:body>
</html:html>
<?xml version="1.0"?>
<!-- 两个命名空间始终都有效 -->
<bk:book xmlns:bk='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<bk:title>Cheaper by the Dozen</bk:title>
<isbn:number>1568491379</isbn:number>
</bk:book>
5.2 命名空间的缺省情况
缺省命名空间适用于声明它的元素(如果那个元素没有命名空间前缀)和所有该元素内容中所有没有前缀的元素。假如在缺省命名空间声明里的 URI 引用为空,那么在声明范围内没有前缀的元素不被认为存在任何命名空间里。注意缺声命名空间不直接适用于属性。<?xml version="1.0"?>
<!-- elements are in the HTML namespace, in this case by default -->
<html xmlns='http://www.w3.org/TR/REC-html40'>
<head><title>Frobnostication</title></head>
<body><p>Moved to
<a href='http://frob.com'>here</a>.</p></body>
</html>
<?xml version="1.0"?>一个较大的命名空间范围的例子:
<!-- unprefixed element types are from "books" -->
<book xmlns='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<title>Cheaper by the Dozen</title>
<isbn:number>1568491379</isbn:number>
</book>
<?xml version="1.0"?>缺声命名空间可被设为空字符串。在声明范围内效果跟没有缺省命名空间相同。
<!-- 开始,缺省的命名空间是 "books" -->
<book xmlns='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<title>Cheaper by the Dozen</title>
<isbn:number>1568491379</isbn:number>
<notes>
<!-- 使 HTML 成为某些注释的缺省命名空间 -->
<p xmlns='urn:w3-org-ns:HTML'>
This is a <i>funny</i> book!
</p>
</notes>
</book>
<?xml version='1.0'?>
<Beers>
<!-- 现在缺省的命名空间是 HTML -->
<table xmlns='http://www.w3.org/TR/REC-html40'>
<th><td>Name</td><td>Origin</td><td>Description</td></th>
<tr>
<!-- 在表格的单元格里无缺省的命名空间 -->
<td><brandName xmlns="">Huntsman</brandName></td>
<td><origin xmlns="">Bath, UK</origin></td>
<td>
<details xmlns=""><class>Bitter</class><hop>Fuggles</hop>
<pro>Wonderful hop, light alcohol, good summer beer</pro>
<con>Fragile; excessive variance pub to pub</con>
</details>
</td>
</tr>
</table>
</Beers>
5.3 属性的单一性
在遵从本规格说明的 XML 文档里,没有任何一个标签可包含两个属性,这些属性:1.具有相同名字,或
2.为具有相同局域部分和有绑定于相同的命名空间名字的前缀的合法名。
比如,下面每一个 bad 的起始标签都不正确:
<!-- http://www.w3.org is bound to n1 and n2 -->但是,下面的都正确,第二个是因为缺声命名空间不适用于属性名:
<x xmlns:n1="http://www.w3.org"
xmlns:n2="http://www.w3.org" >
<bad a="1" a="2" />
<bad n1:a="1" n2:a="2" />
</x>
<!-- http://www.w3.org is bound to n1 and is the default -->
<x xmlns:n1="http://www.w3.org"
xmlns="http://www.w3.org" >
<good a="1" b="2" />
<good a="1" n1:a="2" />
</x>
如果你喜欢这篇文章,请阅读本文相关的下列内容:
比本文新的文章:
