zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    查找算法:二分查找法(折半查找)
    钞票找零-贪心,动态规划算法
    PHP7与php5
    网站高并发解决方案(理论知识) 二
    loj#6566. 月之都的密码
    我的 Linux 配置
    CTSC2011 幸福路径
    WC2018 即时战略
    uoj#460 新年的拯救计划
    bzoj 5016 一个简单的询问
  • 原文地址:https://www.cnblogs.com/philzhou/p/2969343.html
Copyright © 2011-2022 走看看