您能否告诉我如何修复我的代码?我尝试了很多方法,例如使用XmlSerializer,但仍然没有。 代码总是保存列表的最后一项,我不知道如何解决它。 代码:
foreach (ObservableCollection<Person> x in list)
{
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Person",
from person in x
select new XElement("Person",
new XElement("Name", person.Name),
new XElement("Surname", person.Surname),
new XElement("Age", person.Age))));
xdoc.Save(path);
}
我会很高兴任何提示!
答案 0 :(得分:2)
从我理解的评论中你有一个列表列表,你想在生成的XML中展平它。你可以用这个:
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Persons",
from x in list
from person in x
select new XElement("Person",
new XElement("Name", person.Name),
new XElement("Surname", person.Surname),
new XElement("Age", person.Age))));
xdoc.Save("tmp.xml");
您的解决方案不起作用,因为您在foreach
循环的每次迭代中保存了XML文档,这将覆盖现有文件,因此结果将只是循环的最后一次迭代
答案 1 :(得分:0)
他是一个略有不同的xml linq解决方案:
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("People"));
XElement people = xdoc.Root;
foreach (ObservableCollection<Person> x in list)
{
XElement person = new XElement("Person", fom person in x
select new XElement("Person",
new XElement("Name", person.Name),
new XElement("Surname", person.Surname),
new XElement("Age", person.Age)));
people.Add(person);
}
xdoc.Save(path);