我的xml
<?xml version="1.0" encoding="utf-8" ?>
<Category>
<Youth>
</Youth>
<GeneralStores>
</GeneralStores>
<Schools>
</Schools>
<Colleges>
</Colleges>
<GovernmentOffices>
</GovernmentOffices>
<Restaurants>
</Restaurants>
<MovieTheatres>
</MovieTheatres>
</Category>
我需要像
这样的数据表_______________________
Category
__________
Youth
GeneralStores
Schools
Colleges
GovernmentOffices
Restaurants
MovieTheatres
我将此数据表绑定到需要数据源事件的telrik rad网格
这是我的.cs代码
protected void CategoriesRadGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
try
{
//create the DataTable that will hold the data
DataTable CategoryDT = new DataTable("MainCategory");
CategoryDT.Columns.Add("Category", System.Type.GetType("System.String"));
CategoryDT.ReadXml(@"C:\Users\MyID\Documents\Visual Studio 2010\Projects\SomeName\InfoXML\XMLCategory.xml");
}
catch (Exception ex)
{
}
}
答案 0 :(得分:2)
使用XmlDocument读取XML
XmlDocument doc= new XmlDocument();
doc.Load("physical path to file.xml");
// doc.LoadXml(stringXml);
DataTable dt = new DataTable();
if(doc.ChildNodes[1]!=null)
dt.Columns.Add(doc.ChildNodes[1].Name); //Assuming you want the rood node to be the only column of the datatable
//iterate through all the childnodes of your root i.e. Category
foreach(XmlNode node in doc.ChildNodes [1].ChildNodes )
{
dt.Rows.Add(node.Name);
}
答案 1 :(得分:0)
尝试以下方法:
private static DataTable BuildDataTable(XElement x)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn(x.Name.ToString()));
foreach (var d in x.Descendants())
{
DataRow drow = dt.NewRow();
drow[0] = d.Value;
dt.Rows.Add(drow);
}
return dt;
}
该方法将遍历xml并创建dataTable。 Xelement
是linq的一部分,需要.Net框架4.它代表一个XML元素。
调用方法:
//this answers your second question,
//use Server.MapPath to find your file.
XElement x = XElement.Load(Server.MapPath(".") + @"\test.xml");
DataTable dt = BuildDataTable(x);