Web Design. Development. Optimization. RSS 2.0
 Friday, May 07, 2004

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.

 

Friday, May 07, 2004 4:17:47 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
Technology | .NET
Del.icio.us Digg Technorati Blinklist Furl reddit
Comments are closed.
Archive
<October 2008>
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Scott Duffy
Sign In
Statistics
Total Posts: 474
This Year: 34
This Month: 4
This Week: 0
Comments: 73
Themes
Pick a theme:
All Content © 2008, Scott Duffy
DasBlog theme 'Business' created by Christoph De Baene (delarou)