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.