1
  <?xml version="1.0"?>
     <configuration  xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
         <configSections>

我有一个 web.config 文件,其中包含配置标记中的 xmlns。

我想删除一个特定的节点。但我无法读取此文件。

下面是代码:

XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(PATH + WEB_CONFIG_PATH);
        //XmlNode t = xmlDoc.SelectSingleNode("/system.webServer/handlers  /add[@path='Reserved.ReportViewerWebControl.axd']");
        XmlNode t = xmlDoc.SelectSingleNode("/configuration/system.webServer");
        if (t != null)
        {
            t.ParentNode.RemoveChild(t);
            xmlDoc.Save(PATH + WEB_CONFIG_PATH);
        }

如果我从配置标记中删除 xmlns,则此代码可以正常工作。

请提供一些解决方案,以便在存在 xmlns 时此代码可以工作。

4

1 回答 1

3

您需要通过在代码中添加 a 并在调用中XmlNamespaceManager使用它来添加对 XML 命名空间的支持。SelectSingleNode此外,您需要调整调用的 XPath 以包含 XML 命名空间前缀:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(PATH + WEB_CONFIG_PATH);

// add a XmlNamespaceManager to deal with the XML namespaces in your XML document        
XmlNamespaceManager xmlNsMgr = new XmlNamespaceManager(xmlDoc.NameTable);

// add an explicit XML namespace with prefix. NOTE: for some reason, the approach of using
// an empty string indicating a *default* XML namespace doesn't work with .NET's XmlDocument
xmlNsMgr.AddNamespace("ns", "http://schemas.microsoft.com/.NetConfiguration/v2.0");

// tweak your call - use the XML namespace prefix in your XPath, provide the namespace manager
XmlNode t = xmlDoc.SelectSingleNode("/ns:configuration/ns:system.webServer", xmlNsMgr);

if (t != null)
{
    ......
于 2013-01-08T06:22:40.377 回答