Поделиться через


Default Namespaces and XML: Who Knew!?!?

I work a lot with XML and XML will obviously play an important role in future development. Over the last couple of months, I've been observing some incredibly strange behaviors with namespaces. I was certain that I must be observing a bug in Microsoft's XML Parsers, so today I decided I was going to finally figure out what was happening.

Take the following example:

 <html xmlns="https://www.w3.org/1999/xhtml"> 
    …     
    <a href="http:someurl" >     
    … 
</html> 

Question #1: What is that namespace for the "a" element?

Answer #1: It's "https://www.w3.org/1999/xhtml" .

Question #2: What is the namespace for the "href" attribute?

Answer #2: Did you say "https://www.w3.org/1999/xhtml" ? Wrong! It's actually null!

What? That didn't make any sense, so then I tried using an explicit prefix on the elements…

 <h:html xmlns:h="https://www.w3.org/1999/xhtml"> 
     … 
     <h:a href="http:someurl" > 
     … 
</h:html> 

When you use an explicit prefix on elements then the namespace for both "a" and "href" becomes "https://www.w3.org/1999/xhtml" .

This certainly seemed like a bug, so I went straight to the source. . . the W3C.

https://www.w3.org/TR/2006/REC-xml-names-20060816/#scoping

Amazingly enough, it's not a bug! If you use a default namespace, then elements with no prefix belong to the default namespace; however, attributes have a null namespace. If you use a namespace prefix on elements, then attributes with no prefix have the same namespace as their containing element!

I have absolutely no idea why the W3C chose this behavior, but it's incredibly important if you are trying to write XPath expressions or are using the Microsoft XML classes.

Understanding this behavior should save you from a lot of frustration!

Happy Coding!