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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.