DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("value", typeof(string));
string Result = "";
string filename = AppDomain.CurrentDomain.BaseDirectory + "Dispose.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNode xmlNode = xmlDoc.SelectSingleNode("DocumentElement");
foreach (XmlNode exMe in xmlNode)
{
XmlNode modeuleNode = exMe.SelectSingleNode("name");
foreach (XmlNode tipMessageNode in modeuleNode)
{
DataRow dr = dt.NewRow();
dr["name"] = tipMessageNode.InnerText;
XmlNode valueNode = exMe.SelectSingleNode("value");
foreach (XmlNode tipValueNode in valueNode)
{
dr["value"] = tipValueNode.InnerText;
}
dt.Rows.Add(dr);
}
}
return dt;
这个太多了,最简单的:
DataSet ds=new DataSet();
DataTable dt=new DataTable();
ds.ReadXml("c:\\new.xml");
dt=ds.Tables[0];
或
public static DataTable CXmlToDataTable(string xmlStr)
{
if (!string.IsNullOrEmpty(xmlStr))
{
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
DataSet ds = new DataSet();
//读取字符串中的信息
StrStream = new StringReader(xmlStr);
//获取StrStream中的数据
Xmlrdr = new XmlTextReader(StrStream);
//ds获取Xmlrdr中的数据
ds.ReadXml(Xmlrdr);
if(ds!=null && ds.Tables[0]!=null){return ds.Tables[0];}
else{return null;}
}
catch (Exception e)
{
throw e;
}
finally
{
//释放资源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
else
{
return null;
}
}
http://www.cnzzlu.com/test/Dlp/19/200912/22-12082.html
string str = "";
using (StreamReader sr = new StreamReader("文件地址", System.Text.Encoding.GetEncoding("GB2312")))
{
str = sr.ReadToEnd();
}
MatchCollection mth = Regex.Matches(str, "<Node><name>([^<]+)</name><value>([^<]+)</value></Node>");
DataTable dt = new DataTable();
for (int i = 0; i < mth.Count; i++)
{
DataRow dr = dt.NewRow();
dr[0] = mth[i].Groups[1].Value;
dr[1] = mth[i].Groups[2].Value;
dt.Rows.Add(dr);
}
return dt;
我们必须知道目标数据表的定义或者格式才能把数据加过去
试试下面的吧
string xmlData="<?xml version=\"1.0\" encoding=\"utf-8\" ?><DocumentElement><Node><name>aaa</name><value>1</value></Node><Node><name>bbb</name><value>0</value></Node></DocumentElement>";
//定义DataTable结构
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("name", typeof(string)));
dt.Columns.Add(new DataColumn("value", typeof(int)));
//加载XML数据,也可XElement.Load("文件名")
var xdoc=XElement.Parse(xmlData);
var m = (from mod in xdoc.Elements("Node")
select new
{
//给DataTabel添加数据行
a=dt.Rows.Add(new[]{mod.Element("name").Value,mod.Element("value").Value})
}).ToList();