• 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);
    }
  • 相关阅读:
    Codeforces Round #631 (Div. 2)
    Codeforces Round #500 (Div. 2) [based on EJOI]
    KMP+状态机
    状态机模型
    最短编辑距离
    stringstream读入-最优乘车
    多重背包
    Codeforces:B. New Year and Ascent Sequence
    查找目录下所有文件使用到的宏
    QProcess调用外部程序并带参执行
  • 原文地址:https://www.cnblogs.com/philzhou/p/2969343.html
Copyright © 2020-2023  润新知