Ignoring XPath Namespaces

08 December 2010

XML namespaces might be useful for resolving conflicts when combining segments from multiple XML entitied into a single file. They can also be extremely useful for versioning large complicated documents. But, to most developers who are merely trying to accomplish simple tasks in a short amount of time, they are nothing more than obstacles.

It is still common to see code that uses XmlNamespaceManager syntax when trying to adjust for namespaces. I have always felt that this syntax was overkill and overly complicated for everyday situations. It is also hard to remember, so there is a lot of copy-and-paste inheritance. Worst of all, it does not work for nearly identical documents that do not include the namespace.

1 public XmlNodeList GetProjectReferences(XmlDocument xml)
2 {
3  var nsMgr = new XmlNamespaceManager(xml.NameTable);
4  nsMgr.AddNamespace("ns", 
5   "http://schemas.microsoft.com/developer/msbuild/2003");
6  var nodes = xml.SelectNodes("//ns:ProjectReference/@Include", 
7   nsMgr);
8  return nodes;
9 }

A simpler way of handling this problem is to modify the syntax of the XPaths themselves. For example, the following code accomplishes the same return for documents containing namespaces, but it still works on similar xml where the namespaces are excluded. I also feel that it is much easier to remember.

1 public XmlNodeList GetProjectReferences(XmlDocument xml)
2 {
3  var nodes = xml.SelectNodes("//*[local-name()='ProjectReference']/@Include");
4  return nodes;
5 }