使用XML名称空间
在搜索Web时,我遇到了许多在XML文件中使用名称空间的例子。他们大多有这样的形式:使用XML名称空间
<d:student xmlns:d='http://www.develop.com/student'>
<d:id>3235329</d:id>
<d:name>Jeff Smith</d:name>
<d:language>C#</d:language>
<d:rating>9.5</d:rating>
</d:student>
(从https://msdn.microsoft.com/en-us/magazine/cc302166.aspx采取这个例子)
这条线:
<d:student xmlns:d='http://www.develop.com/student'>
麻烦我,几乎因为每一个例子看起来是这样的。它可以有
<student xmlns:d='http://www.develop.com/student'>
所以在这里我声明由同一个URI标识相同的命名空间形式,但我不希望节点,在申报是有命名空间。这是对的吗?长话短说:just xmlns:d='http://www.develop.com/student'
命名空间的有效声明是d:
?
xmlns:d='http://www.develop.com/student'
将声明该元素及其所有后代的d
命名空间。
如果标签名称上缺少d:
,则不会使该元素来自该名称空间。这仍然会使用默认的命名空间。
即
<foo xmlns="http://example.com/1">
<bar xmlns:x="http://example.com/2">
<x:baz />
</bar>
</foo>
foo
来自/1
。 bar
来自/1
。 baz
来自/2
。
d
不是命名空间,而是它的别名(可用作前缀)。命名空间仍然是http://www.develop.com/student
。
<d:student xmlns:d='http://www.develop.com/student'/>
可以被解读为{http://www.develop.com/student}:student
。
可以使用xmlns属性为没有前缀的元素定义默认名称空间。所以<student xmlns='http://www.develop.com/student'/>
也可以看作{http://www.develop.com/student}:student
。
DOM实际上将名称空间和本地名称保存在节点对象的不同属性中。 {namespace}:localname
语法通常用于调试输出。
namspace定义对于定义在其上的元素节点及其所有后代(除非它在后代中被覆盖)始终有效。
属性节点不使用默认名称空间定义。没有前缀的属性总是在“空”名称空间中。
这是一个不使用前缀的例子。
<student xmlns="http://www.develop.com/student">
<id>3235329</id>
<name>Jeff Smith</name>
<description type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml/">
...
</div>
</description>
</student>
该示例中的节点名(与解析名称空间)为:
{http://www.develop.com/student}:student
{http://www.develop.com/student}:id
{http://www.develop.com/student}:name
{}:type
{http://www.w3.org/1999/xhtml/}:div