Wednesday, March 13, 2013

Convert XElement to DataTable

public DataTable XElementToDataTable(XElement x)
   DataTable dt = new DataTable();

  XElement setup = (from p in x.Descendants() select p).First();
   foreach (XElement xe in setup.Descendants()) // build your DataTable
     dt.Columns.Add(new DataColumn(xe.Name.ToString(),typeof(string))); // add columns to your dt

  var all = from p in x.Descendants(setup.Name.ToString()) select p;
   foreach (XElement xe in all)
     DataRow dr = dt.NewRow();
     foreach (XElement xe2 in xe.Descendants())
       dr[xe2.Name.ToString()] = xe2.Value; //add in the values
   return dt;

No comments:

Post a Comment