c#中的XML字符串到DataTable

时间:2011-10-18 01:57:21

标签: c# .net xml datatable

如何在c#中将XML字符串转换为DataTable?

我尝试了以下代码:

    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;

    }

并返回一个空的DataTable。

1 个答案:

答案 0 :(得分:53)

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

    return theDataSet.Tables[0];
}

您可以使用StringReader将其加载到DataSet。从那里,具有第一个索引的表将包含DataTable