Search code examples
xmlvb.netweb-configxmldocument

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


Am getting error object variable or with block variable not set while SelectSingleNode from xml document

Here is my code

 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") in this am getting "Nothing" as string

In my web.config i have

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

xmlns in configuration section .

If i removed from "xmlns" from configuration tag i am able to update my web.config . if i kept this am getting object variable or with block variable not set error while SelectSingleNode from xml


Solution

  • Your XML has default namespace (namespace declared without prefix). Descendant elements inherit ancestor default namespace implicitly, unless otherwise specified. To access element in namespace, you need to map a prefix to point to the namespace uri, and then use that prefix in your 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")