24

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.

1 Answer 1

73
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.

Sign up to request clarification or add additional context in comments.

1 Comment

A long search have found an end with your answer! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.