set datatable id carefully when using readxml
As many of you know there are easy ways to read the contents of an xml file using the .net framework.
The choice I prefer for flat files is the ReadXML() method and for the longest time I could only get this to work with a dataSet and not the datatable. Frustrated by this I worked until I figured out my issue. Hopefully this helps someone else who has this issue.
When you call ReadXml() on a dataset you need no schema, or anything for that matter. You can do this for example:
dim ds as new dataset
ds.readxml(filename)
and your xml data is available in your tables collection in the table at index 0. Column names are inferred from node entries in the original document. It’s quick and dirty but it works and you don’t have to spend too much time on the logic. I expected similar results with the datatable but I did not get that.
Datatables MUST have a schema for the readxml() call to succeed. They also must have one more thing and that is an appropriately set name. The name must match the parent xml node of your actual file. Since we are reading directly to a datatable here we can assume your xml file is pretty simple otherwise you would be using the dataset.
Lets say your xml file has a root node, a node inside of that called “SqlParameters”, and inside of “SqlParameters” is a bunch of other nodes. You will want to make sure that your datatable’s name/id property is “SqlParameters” (or whatever yours is called). The datatable name is important because it provides a hook that the schema uses to map with the values from your xml file. In short, if you don’t set the name then the readxml call has no clue where to put the data so it errors out.
Another step required is to read in the xml file’s schema. You have to read in the schema before you call readxml on your datatable. I have found the easiest way to get a schema file is to open your xml file in visual studio and then click on the xml menu overhead and choose “create schema” and then save the outputted file. The drawback to this is that every time you make a edit to the xml file you will want to update the schema too. But, its easier than doing it by hand. Xml is tricky!
so, back to our example above with the “SqlParameters” xml file. Let’s say it’s called sqlparameters.xml and the schema is sqlparameters.xsl.
dim dt as new datatable(”SqlParameters”) ‘create table with name
dt.readxmlschema(”sqlparameters.xsl”) ‘read schema first
dt.readxml(”sqlparameters.xml”) ‘now read xml file
I will come back and update the code examples when I figure out why my [code] tag is not working.













