Condividi tramite


A Quick Primer on Namespace Bindings

I sent an email trying to explain to a customer why their SOAP packet was not being processed correctly.  In effect, the problem was that an element that was supposed to be bound to https://tempuri.org was redefining its namespace binding using xmlns="".  A quick example:

 
<transportation xmlns="https://tempuri.org">  <bus />  <car xmlns="">    <chevrolet />    <ford />  </car>  <t:motorcycle xmlns:t="urn:transports:types">    <harley />    <honda />  </t:motorcycle>  <bicycle /></transportation>

The expectation was that the "chevrolet" element would be in the https://tempuri.org namespace.  As you can see, the element is not bound to a namespace because we specified xmlns="".  In fact, if we run through the elements using an XML parser, you will see the namespace bindings.

Element Name Namespace Binding
transportation https://tempuri.org
bus https://tempuri.org
car
chevrolet
ford
t:motorcycle urn:transports:types
harley https://tempuri.org
honda https://tempuri.org
bicycle https://tempuri.org

The other part that can be confusing is how namespace prefixes fit into this.  Notice that the motorcycle element is bound to the urn:transports:types namespace, but its child elements are bound to the https://tempuri.org namespace.  Children inherit the namespaces of their parent element unless otherwise declared.  Using a namespace prefix is one way to specify the namespace binding for an element rather than simply inherit the binding from a parent element.

The other part that seems confusing through proliferation on blogs and newsgroups is what to call the condition xmlns="".  It is sometimes referred to as "the empty namespace", which Tim Bray points out is technically incorrect.  As Tim points out, either an element is bound to a namespace or not.