Using DataSets to Process XML
I started a project recently that requires me to process an XML file from Google. Being the lazy sort, I’d really rather just use the data as though it were part of a database and forget that it was ever XML. So I’m using a method in the DataSet class that I’m finding is rather obscure. ReadXml().
This little function will take ANY XML file path as a parameter and will load it into an untyped dataset. I’ve used it before to load RSS feeds and databind to them. You’ll need to run the debugger to find out exactly which table in the dataset has the data you are interested in. In this case, I found that Tables[4] was the table I wanted.
DataSet ds = new DataSet(); ds.ReadXml(openFileDialog1.FileName); foreach(DataRow dr in ds.Tables[4].Rows)
But as I pondered the situation more, I realized that what I really wanted was the XML in a typed dataset. Creating a typed dataset with the name of the table and the rows in that table with the same name as what they showed up in my untyped dataset didn’t quite do the trick. However, I was able to use this loop to get the data out of my untyped dataset into my typed dataset without having to spend a lot of time determining which fields were in both. In fact, the code below will allow me to change my typed dataset and/or the data I’m having Google put in my XML file without having to change this loop at all.
DataSetAdWords dsa = new DataSetAdWords(); DataSet ds = new DataSet(); ds.ReadXml(openFileDialog1.FileName); foreach(DataRow dr in ds.Tables[4].Rows) { DataSetAdWords.rowRow r = dsa.row.NewrowRow(); foreach(DataColumn dc in dsa.row.Columns) { r.SetField(dc, dr.ItemArray[ds.Tables[4].Columns[dc.ColumnName].Ordinal]); } dsa.row.AddrowRow(r); }
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!


August 6th, 2008 at 4:52 am
Be aware that this does not work with any ad-hoc XML as the DataSet can’t consume XML where one typed child can have more than one typed parent. Have you considered LINQ to XSD as an alternative?
August 6th, 2008 at 5:38 am
I haven’t run into that situation and this isn’t the first time I’ve tried this. So, until I do, I’m going to continue to use this simple method.