xmlns + SelectNodes = empty XmlNodeList

Trying to parse web.config files using SelectNodes, I found that I have two kinds of web.config files on my development PC, one with an xmlns declaration and one without.


This should not really bother me, but it turns out that the SelectNodes method does not work as expected when an xmlns declaration is present. As this comment points out, a namespace manager definition is needed, and the namespace needs to be added to the manager. That’s because, the .Net runtime cannot do this for you.

The namespace of the XML document can be retrieved from DocumentElement.NamespaceURI.

As a ridiculous consequence, every XPath query has to include the namespace in every tag!

So, my previously single-line solution to iterate all user control namespaces in the web.config gained some weight, but fortunately it works:

XmlDocument docWC = new XmlDocument();

XmlNamespaceManager mgr =
    new XmlNamespaceManager(docWC.NameTable);
XmlNodeList xnl = null;
if (string.IsNullOrEmpty(docWC.DocumentElement.NamespaceURI))
    xnl = docWC.SelectNodes(
        "/configuration/system.web/pages/controls/add", mgr);
    mgr.AddNamespace("gr", docWC.DocumentElement.NamespaceURI);
    xnl = docWC.SelectNodes(
        +"gr:add", mgr);

1 thought on “xmlns + SelectNodes = empty XmlNodeList

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.