需要使用循环在Xml Child中存储记录

时间:2013-10-04 10:36:38

标签: c# xml linq-to-xml

我要求从列表中添加数据<>到xml文件。我正在使用XDocument并创建元素来在xml中创建和存储数据。现在我有多个,我试图使用foreach循环来存储人员数据STAFFID,但它给了我错误。

public void generateXMLFile(List<UWL> myList )
{          
        XDocument objXDoc = new XDocument(
        new XElement("Institution",
         new XElement("RECID", myList[0].recid),
         new XElement("UKPRN", myList[0].UKPRN),
         new XElement("Person",

             foreach(var m in myList)
             {
                new XElement("STAFFID", m.STAFFID)
             } 
          )
         )
        );

        objXDoc.Declaration = new XDeclaration("1.0", "utf-8", "true");
        //
        objXDoc.Save(@"C:\Test\generated.xml");

        //Completed.......//
        MessageBox.Show("Process Completed......");
}

1 个答案:

答案 0 :(得分:1)

您需要为Person元素提供内容。 Foreach循环不返回任何内容。因此,有效的代码将是:

XDocument objXDoc = new XDocument(
  new XElement("Institution",
   new XElement("RECID", myList[0].recid),
   new XElement("UKPRN", myList[0].UKPRN),
   new XElement("Person",
       myList.Select(m => new XElement("STAFFID", m.STAFFID))
  )
 )
);

创建STAFFID元素的集合,并将此集合设置为Person元素的内容。