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.
You need to add node created in loop to
AUTHORDATAnode: