0

Setup:

I have some xml data stored in a database (SQL Server 2008 R2) which is retrieved via stored proc and placed into a DataTable. The DataTable has 2 columns: a DateTime "timestamp", and an XML "info".

After pulling this data from the database, I would like to loop through each row and operate on the data using LINQ to XML in C#.

public static void ParseDataTable(DataTable dataTable)
{
    for (int r = 0; r < dataTable.Rows.Count; r++)
    {
        // dataTable.Rows[r]["timestamp"].ToString() holds DateTime
        // dataTable.Rows[r]["info"].ToString() holds XML
    }
}

My Question:

What is the simplest way to get this data into an object on which I can use LINQ? What types of objects should be used?

Furthermore:

  • Please don't ask why xml is stored in the database, or recommend a different storage medium. Not looking to start a holy war.
  • If the xml should be returned as a different type (e.g., CAST([info] AS VARCHAR(MAX))), please let me know.
  • I would rather like to use LINQ to parse the object, once I have it available, so please do not recommend other methods.

Thanks in advance.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
Nick Vaccaro
  • 5,428
  • 6
  • 38
  • 60

1 Answers1

2
XDocument doc = XDocument.Parse(dataTable.Rows[r]["info"].ToString());

And then you can linq away

Community
  • 1
  • 1
Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
  • So easy! Thank you. I hadn't stumbled across XDocument.Parse(), which makes this very simple. Plus, linking back to a Jon Skeet answer - always good. :D – Nick Vaccaro Oct 29 '12 at 19:18
  • It may be better to use `XElement.Parse` unless the XML in question is a full document -- see [here](http://msdn.microsoft.com/en-us/library/bb675196.aspx) and [here](http://stackoverflow.com/questions/1671542/whats-the-difference-between-xelement-load-and-xdocument-load). – Zev Spitz Jun 29 '13 at 21:06