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);
}

Related Post

2 Responses to “Using DataSets to Process XML”

  • 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?

  • Dave:

    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.

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear