[Solved] XML SelectNodes not working

You are loading an XMLDocument, and when trying to use XPath to get some nodes, plop… zero count.


The problem:

Dim xmlDoc As New Xml.XmlDocument()

xmlDoc.Load("XMLData.xml")

Dim nodeList = xmlDoc.DocumentElement.SelectNodes("//NodeName") returns nothing!


The cause:

Your XML document has a namespace (xmlns) attribute in its root node, and if you don’t specify it in the SelectNodes method, it just doesn’t work. God knows what’s the reasoning behind this, but that’s how it is.


The solution:

Dim xmlDoc As New Xml.XmlDocument()

xmlDoc.Load("XMLData.xml")

Dim nsmgr As New Xml.XmlNamespaceManager(xmlDoc.NameTable)
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.Attributes("xmlns").Value)


Dim nodeList = xmlDoc.DocumentElement.SelectNodes("//ns:NodeName", nsmgr)


There you go, you need to declare a Namespace Manager and specify it in the SelectNodes method.

Hope this works for you!



2 comments
Posted by Berndawg on 6/25/2020 3:55:05 PM
I was about to commit suicide. You saved me. Thank you very much!
Posted by poppitee on 1/2/2021 11:20:45 PM
Thank you so much for this post! After 3 hours of researching, your solution worked!
Leave a comment
Display Name:  


Email:    


Comment:  



Domain Registrations starting at $9.69
Powered by Carlos Bercero Blog Platform © 2009