Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML string to DataTable in C#

How to convert XML string to DataTable in C#?

I tried the following code:

public DataTable stam()
{
    string xmlData = "<Names><Name>a</Name><Name>b</Name><Name>c</Name><Name>d</Name></Names>";

    XElement x = XElement.Parse(xmlData);

    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
        dt.Rows.Add(dr);
    }

    return dt;
}

and it returns an empty DataTable.

like image 714
user990635 Avatar asked Oct 18 '11 01:10

user990635


1 Answers

public DataTable stam()    
{
    StringReader theReader = new StringReader(xmlData);
    DataSet theDataSet = new DataSet();
    theDataSet.ReadXml(theReader);

    return theDataSet.Tables[0];
}

You can use a StringReader to load it into a DataSet. From there, the table with the first index will contain the DataTable.

like image 188
Patrick Desjardins Avatar answered Oct 18 '22 14:10

Patrick Desjardins