如何在代码中维护 xml 文件的树结构并访问 "subtags"?

How can I maintain the treestructure of my xml-file in the code and access the "subtags"?

嘿,有个小问题, 我有一个结构如下的 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);
        }

使用此方法不会将它们添加到集合中。如何从加载的 XElements 中获取不同的节点并将它们存储在 ObservableCollection 中?还是有更简单的方法来做到这一点? 已经谢谢了:)

我喜欢将结果放入数据表中,您可以随时将其绑定到可观察的视图。我使用 xml linq 来解析 xml

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();
            }

        }
    }
}