Error : vb selectsinglenode object variable or with block variable not set

Error : vb selectsinglenode object variable or with block variable not set

从 xml 文档

中选择 SelectSingleNode 时出现错误对象变量或未设置块变量

这是我的代码

 sWC = My.Computer.FileSystem.ReadAllText("c:\inetpub\" & sServer & "\web.config")
    Dim xmlDoc = New XmlDocument()
    xmlDoc.Load("c:\inetpub\" & sServer & "\web.config")

  Dim nodeRegion = xmlDoc.CreateElement("add")
        nodeRegion.SetAttribute("key", sAppPool)
        nodeRegion.SetAttribute("value", "Sunday,12:00 AM")
        xmlDoc.SelectSingleNode("//appSettings").AppendChild(nodeRegion)
        xmlDoc.Save("c:\inetpub\" & sServer & "\web.config")

xmlDoc.SelectSingleNode("//appSettings") 在这里得到 "Nothing" 作为字符串

在我的 web.config 我有

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> 

xmlns 在配置部分。

如果我从配置标签中删除 "xmlns",我就可以更新我的 web.config。 如果我保留这个正在获取对象变量或块变量未设置错误,而 SelectSingleNode 来自 xml

您似乎还没有声明您的 //appSettings 部分。你能 post 你的 XML-文件吗?尝试向其中添加 <appSettings> [.. Your Implementation here ..]</appSettings>! ;)

** 编辑 **

我前段时间遇到了同样的问题。这是我现在在 Visual C++ 中使用的代码。使用两个数组调用 UpdateAppSettings,一个包含键名,另一个包含相应的值。因此,假设您将此函数称为:

UpdateAppSettings(gcnew array<String^>{"key"},gcnew array<String^>{"value"});

...它会将以下内容写入您的 .config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="key" value="value" />
  </appSettings>
</configuration>

也许这样的事情正是您想要做的?

static void Daten::UpdateAppSetting(array<String^>^ names, array<String^>^ newVal) {
            System::Configuration::ExeConfigurationFileMap^ ConfigMap =
                     gcnew System::Configuration::ExeConfigurationFileMap();

            // Here you declare what file ConfigMap should refer to
            ConfigMap->ExeConfigFilename = "C:\{YOURAPPLICATIONNAME}.config";
            // .config file einlesen und Daten in config speichern
            MyConfig = 
                      System::Configuration::ConfigurationManager::OpenMappedExeConfiguration(ConfigMap, ConfigurationUserLevel::None);


            for (int i = 0; i < names->Length; i++) {

                    if (MyConfig->AppSettings->Settings[names[i]] != (nullptr))
                        MyConfig->AppSettings->Settings->Remove(names[i]);

                MyConfig->AppSettings->Settings->Add(names[i], newVal[i]);
            }
            MyConfig->Save(ConfigurationSaveMode::Modified);
            ConfigurationManager::RefreshSection("appSettings");
        }

您的 XML 具有默认命名空间(声明的命名空间没有前缀)。后代元素隐式继承祖先的默认命名空间,除非另有说明。要访问命名空间中的元素,您需要映射一个前缀以指向命名空间 uri,然后在您的 XPath 中使用该前缀:

Dim xmlDoc = New XmlDocument()
xmlDoc.Load("c:\inetpub\" & sServer & "\web.config")
Dim nsmgr As New XmlNamespaceManager(xmlDoc.NameTable)
nsmgr.AddNamespace("d", "http://schemas.microsoft.com/.NetConfiguration/v2.0")
......
......
xmlDoc.SelectSingleNode("//d:appSettings", nsmgr).AppendChild(nodeRegion)
xmlDoc.Save("c:\inetpub\" & sServer & "\web.config")