XML to datatable

CSharp · Console

/Program.cs

using System;
using System.Data;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
					
public class Program
{
	public static void Main()
	{
		var xml =@"<?xml version=""1.0"" encoding=""utf-8""?>
<Root>
  <orders>
    <OrderID>10248</OrderID>
    <CustomerID>VINET</CustomerID>
    <EmployeeID>5</EmployeeID>
    <OrderDate>1996-07-04T00:00:00</OrderDate>
    <RequiredDate>1996-08-01T00:00:00</RequiredDate>
    <ShippedDate>1996-07-16T00:00:00</ShippedDate>
    <ShipVia>3</ShipVia>
    <Freight>32.3800</Freight>
    <ShipName>Vins et alcools Chevalier</ShipName>
    <ShipAddress>59 rue de l'Abbaye</ShipAddress>
    <ShipCity>Reims</ShipCity>
    <ShipPostalCode>51100</ShipPostalCode>
    <ShipCountry>France</ShipCountry>
  </orders>
</Root>";
		var doc = XDocument.Parse(xml);
		var result= doc.Descendants("orders");
		var data = result.ToList();	
		var table =ConvertToDataTable(data);
		foreach(DataRow row in table.Rows){
			foreach(var col in row.ItemArray)
			{
				Console.WriteLine(col);
			}
		}
	}
	
	public static DataTable ConvertToDataTable(IEnumerable<XElement> data)
	{		
		var table = new DataTable();
		// create the columns
		foreach(var xe in data.First().Descendants())
			table.Columns.Add(xe.Name.LocalName,typeof(string));
		// fill the data
		foreach(var item in data)
		{
			var row = table.NewRow();
			foreach(var xe in item.Descendants())
				row[xe.Name.LocalName] = xe.Value;
			table.Rows.Add(row);
		}
		return table;
	}

}

;