命名空间绑定的范围
命名空间绑定(特殊 xmlns
或 xmlns:...
属性)适用于封闭元素的所有后代,包括此元素。
<?xml version="1.0"?>
<root>
<my:element xmlns:my="http://www.example.com/ns1">
<!-- here, the prefix my is bound to http://www.example.com/ns1 -->
</my:element>
<my:element xmlns:my="http://www.example.com/ns2">
<!-- here, the prefix my is bound to http://www.example.com/ns2 -->
</my:element>
</root>
可以在嵌套元素中覆盖绑定(这会影响可读性):
<?xml version="1.0"?>
<my:element xmlns:my="http://www.example.com/ns1">
<!-- here, the prefix my is bound to http://www.example.com/ns1 -->
<my:first-child-element/>
<my:child-element xmlns:my="http://www.example.com/ns2">
<!-- here, the prefix my is bound to http://www.example.com/ns2,
including for the element my:child-element -->
</my:child-element>
<!-- here, the prefix my is bound to http://www.example.com/ns1 -->
<my:last-child-element/>
</my:element>
在根元素中声明所有命名空间绑定是很常见的,这提高了可读性。
<?xml version="1.0"?>
<root
xmlns="http://www.example.com/default-namespace"
xmlns:ns1="http://www.example.com/ns1"
xmlns:ns2="http://www.example.com/ns2">
<ns1:element>
<ns2:other-element/>
</ns1:element>
</root>