里面是一个改写XML文件的函数。用来改写WEB。CONFIG的。
 
当<Configuration带着xmlns时就失败了。如果不带xmlns的话就成功。
 
有办法不?
函数代码:
        public void ModifyXMLSegment(string xmlFileName, string key, string strValue)
        {
            String TargetDir = "D:\\Projects\\Help2005\\UnitTest";
            string XPath = "/configuration xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"/connectionStrings/add[@name='?']";
            XPath = "/configuration/connectionStrings/add[@name='?']";
            XmlDocument domWebConfig = new XmlDocument();            domWebConfig.Load((TargetDir + "\\" + xmlFileName));
            XmlNode addKey = domWebConfig.SelectSingleNode((XPath.Replace("?", key)));
            if (addKey == null)
            {
                throw new ArgumentException("Can't found XML segment <add name='" + key + "' connectionString=.../>");
            }
            addKey.Attributes["connectionString"].InnerText = strValue;
            domWebConfig.Save((TargetDir + "\\" + xmlFileName));
        }调用的代码是:
ModifyXMLSegment("Web.Config", "SqlServer", "lkjalsdjf;lsadflk09u098080");
要修改的Web.Config内容如下:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings>
    <add name="SqlServer" connectionString="Database=eHelpdesk_20061228;Server=Localhost;Integrated Security=SSPI;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

解决方案 »

  1.   

    用不着那么麻烦,下面这样就行了
     //打开配置文件
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            //获取appSettings节点
            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
            //删除appSettings节点中的元素
            appSection.Settings.Remove("addkey1");
            //修改appSettings节点中的元素
            appSection.Settings["addkey2"].Value = "Modify key2's value";
            config.Save();