xml转换成DataTable
一、使用 XML定义DataTable构架
<?xml version="1.0" encoding="utf-8" ?>
<root>
<url>http://10.168.68.227:8080/AlarmInfoService/services/AlarmInfoService</url>
<columns>
<column cname="FP0" ctype="System.Decimal"></column>
<column cname="FP1" ctype="System.Decimal"></column>
<column cname="FP2" ctype="System.Decimal"></column>
<column cname="FP3" ctype="System.Decimal"></column>
<column cname="TIME_STAMP" ctype="System.Int32"></column>
<column cname="C_FP0" ctype="System.Decimal"></column>
<column cname="C_FP1" ctype="System.Decimal"></column>
<column cname="C_FP2" ctype="System.Decimal"></column>
<column cname="C_FP3" ctype="System.Decimal"></column>
<column cname="INT_ID" ctype="System.Int32"></column>
</columns>
</root>
DataTable dt = new DataTable();
XmlDocument doc = new XmlDocument();
string pathurl = System.IO.Directory.GetCurrentDirectory().Replace("Bin\\bin", "") + @"AlarmCreateDataTableConfig.xml";
doc.Load(pathurl);
XmlNodeList xml = doc.GetElementsByTagName("column");
for (int i = 0; i < xml.Count; i++)
{
string dataName = xml.Item(i).Attributes["cname"].Value;
string dataType=xml.Item(i).Attributes["ctype"].Value;
dt.Columns.Add(new DataColumn(dataName, Type.GetType(dataType)));
}
二、另外一种运用方法:
using System;
using System.Data;
using System.Collections;
using System.Xml;
using System.IO;
using System.Text;
namespace ConsoleTest
{
/// <summary>
/// ZZConsole 的摘要说明。
/// </summary>
public class ZZConsole
{
[STAThread]
static void Main(string[] args)
{
XmlDocument xdoc= new XmlDocument();
xdoc.Load(@"d:\test.xml");
DataSet ds = CreatDataSet();
XmlNodeList xList = xdoc.SelectNodes("//Item");
foreach(XmlNode xNode in xList)
{
DataRow dr = ds.Tables["Items"].NewRow();
dr["Item"] = xNode.Attributes["Name"].Value;
ds.Tables["Items"].Rows.Add(dr);
}
foreach(DataRow dr in ds.Tables["Items"].Rows)
{
Console.WriteLine(dr["Item"].ToString());
}
Console.ReadLine();
}
public static DataSet CreatDataSet()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Items");
DataColumn dc = new DataColumn("Item",typeof(string));
dt.Columns.Add(dc);
ds.Tables.Add(dt);
return ds;
}
}
}
=======================================================
<?xml version="1.0" encoding="utf-8" ?>
<Root>
<Class Name="1">
<Item Name="Item11"/>
<Item Name="Item12"/>
<Item Name="Item13"/>
<Item Name="Item14"/>
</Class>
<Class Name="2">
<Item Name="Item21"/>
<Item Name="Item22"/>
<Item Name="Item23"/>
<Item Name="Item24"/>
</Class>
</Root>