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.

<configuration>
<configuration
    xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

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();
docWC.Load("web.config");

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);
}
else
{
    mgr.AddNamespace("gr", docWC.DocumentElement.NamespaceURI);
    xnl = docWC.SelectNodes(
        "/gr:configuration/gr:system.web/gr:pages/gr:controls/"
        +"gr:add", mgr);
}
原文地址:https://www.cnblogs.com/philzhou/p/2969343.html