C#:如何通过自己的字典迭代,在我的XDocument中编写XElements



我得到了一本具有不同属性的字典。现在我想从这个字典中创建一个 XML 文件,但我不知道如何通过字典中的每个条目进行迭代。在我的字典中,有 2 个属性称为数量和价格。

所以这实际上是我的代码的样子。

XDocument xDoc = new XDocument(
            new XElement("itemlist",
                    new XElement("item",
                        new XAttribute("article", "1"),
                        new XAttribute("quantity", "150"),
                        new XAttribute("price", "20"))));
xDoc.Save("C:/Users/User/Desktop/XMLOutput.xml");

但我不想自己写字典中的每个条目,所以我正在寻找这样的解决方案:

XDocument xDoc = new XDocument(
            new XElement("itemlist",
            foreach (KeyValuePair<string, item> it in dictionary_items)
                    {                           
                        new XElement("item",
                           new XAttribute("article", it.Key),
                           new XAttribute("quantity", it.Value.quantity),
                           new XAttribute("price", it.Value.price)
                        ));
                    }
xDoc.Save("C:/Users/User/Desktop/XMLOutput.xml");

所以我想遍历字典中的每个条目,并将其写在我的XML文件中。我该怎么做?

感谢您的帮助。

当然。 你可以使用 XStreamingElement 来实现这一点:

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
namespace ConsoleApp31
{
    class Program
    {
        class Item
        {
            public int quantity { get; set; }
            public double price { get; set; }
        }
        static void Main(string[] args)
        {
            var dictionary_items = new Dictionary<string, Item>();
            dictionary_items.Add("abc", new Item() { quantity = 1, price = 3.3 });
            dictionary_items.Add("def", new Item() { quantity = 1, price = 3.3 });
            XDocument xDoc = new XDocument(
                new XStreamingElement("itemlist",
                     from it in dictionary_items
                     select new XElement("item",
                               new XAttribute("article", it.Key),
                               new XAttribute("quantity", it.Value.quantity),
                               new XAttribute("price", it.Value.price)))
                );
            Console.WriteLine(xDoc.ToString());
            Console.ReadKey();
        }
    }
}

输出

<itemlist>
  <item article="abc" quantity="1" price="3.3" />
  <item article="def" quantity="1" price="3.3" />
</itemlist>
var list = new XElement("itemlist");
foreach (KeyValuePair<string, item> it in dictionary_items)
{                           
    list.Add(new XElement("item",
                           new XAttribute("article", it.Key),
                           new XAttribute("quantity", it.Value.quantity),
                           new XAttribute("price", it.Value.price)
                        )));
}
XDocument xDoc = new XDocument(list);
xDoc.Save("C:/Users/User/Desktop/XMLOutput.xml");

最新更新