问题描述
我想将从数据库中获取的记录保存在一个 XML 文件中,
将 XML 文件中的 x 条记录放入自定义集合 List
处理它们并将更新的项目保存回 XML 文件.
I want to save records fetched from database in an XML file,
take x number of records from XML file into a custom collection List<T>
process them and save updated items back into XML file.
'T' 是一个具有值类型属性的简单对象,类似于 -
'T' is a simple object with value type properties, something like -
public class T
{
public int Id {get; set;}
public string property1 {get; set;}
public string property2 {get; set;}
}
请指导我如何将自定义集合 List
保存到 XML 文件,反之亦然?
Please guide me how can I save custom collection List<T>
to XML file and vice-versa?
另外,因为我没有发送这个 XML 文件,所以按照一些回复中的建议使用 XmlSerializer 是否有意义?
Also, because I am not sending out this XML file, will it make sense to go for XmlSerializer as suggested in some of the replies?
推荐答案
虽然您可以使用序列化程序 - 很多时候这是正确的答案 - 我个人会使用 Linq to XML 这将使您更灵活地了解如何您的 XML 应该看起来像,即从基于您的类的集合 foos
创建以下 XML:
While you could use a serializer - and many times this is the right answer - I personally would use Linq to XML which would allow you to be more flexible on how your XML should look like, i.e. to create the following XML from a collection foos
based on your class:
<Foos>
<foo Id="1" property1="someprop1" property2="someprop2" />
<foo Id="1" property1="another" property2="third" />
</Foos>
您可以使用:
var xml = new XElement("Foos", foos.Select( x=> new XElement("foo",
new XAttribute("Id", x.Id),
new XAttribute("property1", x.property1),
new XAttribute("property2", x.property2))));
这篇关于保存列表<T>到 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!