XML 命名空间学习笔记
什么是 XML 命名空间?
XML 命名空间是一种用于避免元素和属性名冲突的机制。通过在文档中使用命名空间,我们可以为元素和属性赋予唯一的标识符,以便在不同的上下文中使用相同的名称而不会发生冲突。
命名空间的定义
在 XML 文档中定义命名空间需要使用 xmlns
属性。
xmlCopy Code<root xmlns:ns="https://www.example.com/ns">
<ns:element>命名空间的实例</ns:element>
</root>
在这个例子中,xmlns:ns
定义了 ns
命名空间,其值为 https://www.example.com/ns
。在 element
元素中使用了该命名空间,因此该元素的完整名称为 ns:element
。
实例
使用命名空间定义元素
xmlCopy Code<?xml version="1.0" encoding="UTF-8"?>
<notes xmlns:blog="https://www.example.com/xml/blog">
<blog:post>
<blog:title>命名空间的实例</blog:title>
<blog:content>这是一个命名空间实例的内容。</blog:content>
</blog:post>
</notes>
在这个例子中,我们使用 xmlns:blog
定义了 blog
命名空间,并在 post
元素中使用了该命名空间。title
和 content
元素也是使用了该命名空间。
使用默认命名空间定义元素
xmlCopy Code<?xml version="1.0" encoding="UTF-8"?>
<notes xmlns="https://www.example.com/xml/blog">
<post>
<title>命名空间的实例</title>
<content>这是一个命名空间实例的内容。</content>
</post>
</notes>
在这个例子中,我们使用默认命名空间定义了元素。在 notes
元素中,我们使用 xmlns
定义了默认命名空间。由于没有指定前缀,因此在 post
、title
和 content
元素中都使用了默认命名空间。