命名空间绑定(特殊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>