简体   繁体   中英

Save a Dictionary<int, List<Object>> data to XML file using LINQ

I want to write a Dictionary<int, List<Object>> data to XML file. I tried below code:

Dictionary<int, List<Author>> _empdata = new Dictionary<int, List<Author>>();
List<Author> _author1 = new List<Author> { new Author() { id = 1, name = "Tom", age = 25 } };
List<Author> _author2 = new List<Author> { new Author() { id = 2, name = "Jerry", age = 15 } };

_empdata.Add(1, _author1);
_empdata.Add(2, _author2);

string fileName = "Author_" + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
string filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName) + ".xml";

            XElement elem = new XElement("StackOverflow");
            foreach (KeyValuePair<int,List<Author>> pair in _empdata)
            {
                elem = new XElement("AUTHORDATA",
                from item in pair.Value
                select new XElement("AUTHOR",
                       new XElement("ID", item.id),
                       new XElement("NAME", item.name),
                       new XElement("AGE", item.age)
                       ));
            }
            elem.Save(filePath);

My expected output is:

<AUTHORDATA>
  <AUTHOR>
    <ID>1</ID>
    <NAME>Tom</NAME>
    <AGE>25</AGE>
  </AUTHOR>
  <AUTHOR>
    <ID>2</ID>
    <NAME>Jerry</NAME>
    <AGE>15</AGE>
  </AUTHOR>
</AUTHORDATA>

But,I am getting below records in XML file:

 <AUTHORDATA>
   <AUTHOR>
      <ID>2</ID>
      <NAME>Jerry</NAME>
      <AGE>15</AGE>
    </AUTHOR>
 </AUTHORDATA>

It is only writing the last List record in XML file every time. How can I fix this ? Note: The format of the XML file will be like above.

Any help is appreciated.

[EDIT] Awww sorry, I was misunderstanding your request:

XElement ad = new XElement("AUTHORDATA");
XElement elem = new XElement("StackOverflow", ad);

foreach (KeyValuePair<int, List<Author>> pair in _empdata)
{
    ad.Add(new XElement("AUTHORDATA",
        from item in pair.Value
        select new XElement("AUTHOR",
               new XElement("ID", item.id),
               new XElement("NAME", item.name),
               new XElement("AGE", item.age)
    ));
}

elem.Save(filePath);

You need to add node created in loop to AUTHORDATA node:

var authorData = new XElement("AUTHORDATA");
var root = new XElement("StackOverflow", authorData);
foreach (KeyValuePair<int,List<Author>> pair in _empdata)
{
    authorData.Add(
        from item in pair.Value
        select new XElement("AUTHOR",
            new XElement("ID", item.id),
            new XElement("NAME", item.name),
            new XElement("AGE", item.age)
        ));
}

root.Save(filePath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM