XML 序列化/反序列化最佳实践:XmlSerializer 还是 Linq To XML?
如今,将域对象序列化/反序列化到 xml 文档的最佳方法是什么? XmlSerializer 还是 Linq To XML?每种解决方案的优缺点是什么?
Nowadays, what's the best way to serialize/deserialize domain objects into an xml document? XmlSerializer or Linq To XML? What are the pros and cons of each solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是我认为目前使用 Linq to XML 的主要好处。
XmlSerializer 需要默认(无参数)构造函数。因此,如果您要执行任何类型的控制反转并通过构造函数将依赖项传递到类中,则还需要有一个默认构造函数来绕过这些依赖项的注入。这有点违背了使用构造函数注入的全部目的。
当然,使用 Linq to XML,您需要编写自己的序列化代码,但我已经使用
FromXml
和ToXml
等一组方法或只是一个带有 getter 和 setter 的Xml
属性,用于对需要保存的字段进行序列化。我喜欢在代码中进行控制,而不是必须在某些属性上使用属性来忽略它们。Here's the main benefit I see for using Linq to XML nowadays.
XmlSerializer requires a default (parameter-less) constructor. So, if you're doing any kind of inversion of control and passing dependencies into your class via the constructor, you'll need to also have a default constructor that bypasses the injection of those dependencies. That kinda defeats the whole purpose of using constructor injection.
Of course, with Linq to XML, you'll need to write your own serialization code, but I've done that with either a set of methods like
FromXml
andToXml
or simply anXml
property with getter and setter that do the serialization of exactly the fields that need to be saved. I like having that control in code instead of having to use attributes on some properties to have them ignored.