OdeToCode IC Logo

The XML Namespace Tax

Monday, May 5, 2008

While XML literal features in Visual Basic get all the love, the new XElement API for the CLR makes working with XML in C# a bit more fun, too. It's a prime cut of functional programming spiced with syntactic sugar.

One example is how the API works with XML namespaces. When namespaces are present, they demand attention in almost every XML operation you can perform. It's like a tax you need to pay that doesn't pay back any benefits. An old poll on xml-dev once asked people to list their "favorite five bad problems" with XML, to which Peter Hunsberger replied:

  1. Namespaces
  2. Namespaces
  3. Namespaces
  4. Namespaces
  5. Namespaces

And in a different message, Joe English hit the nail on the head:

I'd rather treat element type names and attribute names as simple, atomic strings. This is possible with a sane API, but most XML APIs aren't sane.

The API we had pre .NET 3.5 was a fill-out-this-form-in-triplicate-and-wait-quietly-in-line bureaucracy living inside System.Xml. The new API tries to be a bit saner:

XNamespace xmlns = "http://schemas.foo.com/widgets";        

XDocument doc = new XDocument(
new XElement(xmlns + "Widgets",
new XElement(xmlns + "Widget", new XAttribute("ID", 1)),
new XElement(xmlns + "Widget", new XAttribute("ID", 2))));

Which produces:

<Widgets xmlns="http://schemas.foo.com/widgets">
  <Widget ID="1" />
  <Widget ID="2" />

It's little things you don't notice at first that makes the API easier. Like XNamepace has an implicit conversion from string, and redefines the + operator to combine itself with a string to form a full XName (which also has an implicit string conversion operator).

Someone spent some time designing this API for users instead of for a standards body, and it's much appreciated.

Jeff Gonzalez Monday, May 5, 2008
Agreed. Good stuff - I showed this to a bunch of students in a C# class last week. The people who use a lot of XML were jaw dropped. Everybody else was like "well, yeah, duh... that's obvious." You'd think.

Thomas Eyde Monday, May 5, 2008
I must be missing something, because I can't see the greatness in repeating the namespace three times in one statement. Isn't there a way to say it once that everything should be in the same namespace?
scott Monday, May 5, 2008
Thomas: I like that it is being explicit. The alternative was to go to an XmlDocument, invoke CreateNode, and pass the namespace as a parameter - the last parameter - almost an afterthought :) It was cumbersome and we all ended up writing wrappers and helper methods for those types of operations.
Comments are closed.