XML字符串数据表在C# [英] XML string to DataTable in c#
本文介绍了XML字符串数据表在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何转换XML字符串数据表在C#?
我尝试以下code:
公开数据表斯塔姆()
{
串XMLDATA = "<Names><Name>a</Name><Name>b</Name><Name>c</Name><Name>d</Name></Names>";
的XElement X = XElement.Parse(XMLDATA);
数据表DT =新的DataTable();
的XElement设置=(从对在x.Descendants()选择P)。首先();
的foreach(在setup.Descendants的XElement XE())//建立你的数据表
dt.Columns.Add(新的DataColumn(xe.Name.ToString(),typeof运算(字符串))); //列添加到您的DT
VAR全部来自p在x.Descendants =(setup.Name.ToString())的选择P;
的foreach(的XElement XE在所有)
{
DataRow的博士= dt.NewRow();
的foreach(的XElement XE2在xe.Descendants())
博士[xe2.Name.ToString()] = xe2.Value; //添加中的值
dt.Rows.Add(DR);
}
返回DT;
}
和它返回一个空的DataTable。
解决方案
公开数据表斯塔姆()
{
StringReader theReader =新StringReader(XMLDATA);
数据集theDataSet =新的DataSet();
theDataSet.ReadXml(theReader);
返回theDataSet.Tables [0];
}
您可以使用 StringReader
将其加载到一个数据集
。从那里,表的第一个索引将包含数据表
。
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
.
这篇关于XML字符串数据表在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文