When ReadXml returns blank rows (or no rows)

Here's one I ran into today. I'm programming along in VB.NET and I have an instance where I need to import data from an XML file into a DataSet (or in my case, a DataTable). I had (essentially) the following code.

Dim dt As New DataTable
dt.TableName = "newtable"
dt.ReadXML("c:\test.xml")
' Do stuff with dt.Rows(0)

Great. Well, this LOOKED like it would work. The solution would build without errors. When I ran the program in debug mode, however, I would get an exception error stating.

"There is no row at position 0"

Well WTF? What is this? After a bit of digging and poking around, I found that I had made a mistake by giving my DataTable variable a TableName value. This caused some clashing with the XML file that I was trying to import, as the table names did not match. This resulted in my imported DataTable having zero rows. The solution is to name your DataTable (if you need to) AFTER you import your XML file into the table. Such as...

Dim dt As New DataTable
dt.ReadXML("c:\test.xml")
dt.TableName = "newtable"
' Do stuff with dt.Rows(0)

Filed Under .NET Development
Tags: , , , , , , , ,

Comments

Got something to say?





Comments links could be nofollow free.