• 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);
    }
  • 相关阅读:
    MySQL--CREATE INDEX在各版本的优化
    MySQL--各版本DDL 操作总结
    MySQL--事务隔离级别RR和RC的异同
    MySQL--运维内参中的binlog_summary脚本
    认知:人性
    诉衷情
    初中生读物
    DTO和Entity转换
    layui开发常用插件列表
    mongodb配置
  • 原文地址:https://www.cnblogs.com/philzhou/p/2969343.html
Copyright © 2020-2023  润新知