嘿,有一个小问题,我有一个结构如下的xml文件:
<cars>
<car name="audi" id="123">
<specs fuel="gas"/>
<specs horsepower="150"/>
</car>
<car name="tesla" id="456">
<specs fuel="electric"/>
<specs horsepower="600"/>
</car>
</cars
我正在尝试从代码中的xml读取所有数据并维护树形结构,以便以后可以显示想要的汽车。因此,我使用了一个ObservableCollection。我这样尝试过:
XElement data = XElement.Load(path);
IEnumerable<XElement> elements = data.Elements().Elements();
XmlData = new ObservableCollection<XElement>();
foreach(var item in elements)
{
XmlData.Add(item);
}
使用此方法,不会将它们添加到集合中。如何从加载的XElement中获取不同的节点并将其存储在ObservableCollection中?还是有更简单的方法来做到这一点?已经感谢:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Fuel", typeof(string));
dt.Columns.Add("Horsepower", typeof(int));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement car in doc.Descendants("car"))
{
DataRow newRow = dt.Rows.Add();
newRow["Name"] = (string)car.Attribute("name");
newRow["ID"] = (int)car.Attribute("id");
newRow["Fuel"] = car.Descendants("specs")
.Where(x => x.Attribute("fuel") != null)
.Select(x => (string)x.Attribute("fuel"))
.FirstOrDefault();
newRow["Horsepower"] = car.Descendants("specs")
.Where(x => x.Attribute("horsepower") != null)
.Select(x => (string)x.Attribute("horsepower"))
.FirstOrDefault();
}
}
}
}