-1

我想将Dictionary<int, List<Object>>数据写入 XML 文件。我尝试了以下代码:

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

我的预期输出是:

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

但是,我在 XML 文件中得到以下记录:

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

每次只在 XML 文件中写入最后一个 List 记录。我怎样才能解决这个问题 ?注意:XML 文件的格式如上。

任何帮助表示赞赏。

4

2 回答 2

3

[编辑] Awww 抱歉,我误解了您的要求:

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);
于 2013-01-19T23:24:20.240 回答
2

您需要将循环中创建的节点添加到AUTHORDATA节点:

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);
于 2013-01-19T23:36:06.567 回答