C#:如何遍历自己的字典在XDocument中编写XElement?

时间:2018-12-30 13:42:46

标签: c# xml file

我有一本具有不同属性的字典。现在,我想用这个字典创建一个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文件中。我该怎么办?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

好的。您可以为此使用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>

答案 1 :(得分:1)

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");
相关问题