So I was playing with .NET and XML today, and ran into a strange problem. I was loading in an XML document, and the SelectNodes method was never returning any results. Here is my VB.NET code:
Dim xmldoc As New System.Xml.XmlDocument
xmldoc.Load("C:\Accounts.xml")
Dim xmlroot As System.Xml.XmlNodeList
xmlroot = xmldoc.SelectNodes("account")
I expected this to work and it didn't. xmlroot.Count returned 0. I searched the web for a few examples, and they seemed to confirm I was using SelectNodes correctly. All other examples I could find used it that way.
Now taking a look at the XML created (I used VS .NET 2003 to create the XML), nothing looked odd to me:
<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="http://tempuri.org/Accounts.xsd">
<account acctno="1">
<name>Acct 1</name>
<weight>10</weight>
<value>0.00</value>
</account>
... etc ...
</accounts>
When poking around in the documentation for SelectNodes, I noticed there was an optional second parameter, XmlNamespaceManager. Could the fact that my XML document had a default namespace be messing with my code? So I tried the following:
Dim xmldoc As New System.Xml.XmlDocument
xmldoc.Load("C:\Accounts.xml")
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(xmldoc.NameTable)
nsmgr.AddNamespace("acct", "http://tempuri.org/Accounts.xsd")
Dim xmlroot As System.Xml.XmlNodeList
xmlroot = xmldoc.SelectNodes("//acct:account", nsmgr)
And, lo and behold, it worked. Most experienced .NET and XML developers probably already knew this, but it seems like odd behaviour to me. Anyways, I hope this tip helps someone out there.