从配置标记中包含命名空间的web.config文件中读取和删除节点

时间:2013-01-08 05:59:23

标签: xml web-config

  <?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时此代码可以正常工作。

1 个答案:

答案 0 :(得分:3)

您需要在代码中添加XmlNamespaceManager并在SelectSingleNode调用中使用它来添加对XML命名空间的支持。此外,您需要调整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)
{
    ......
相关问题