如何从 XML 重建 C# 类
我想在 SQL 中保存 ac#.NET 类的实例以供以后检索。我能够使用 LINQ to SQL 添加包含构成该类的所有 xml 的完整记录。
现在我如何检索该 xml 并重建类对象实例?
I would like to save an instance of a c#.NET class in SQL for later retrieval. I am able to use LINQ to SQL to add a record complete with all the xml that makes up the class.
Now how do I retrieve that xml and reconstruct the class object instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将对象序列化为 XML 字符串:
将 XML 字符串反序列化为对象:
Serialize your object to an XML string:
Deserialize an XML string into an object:
正如其他人提到的,序列化可以解决问题,但要注意格式化程序/序列化程序,否则:
将是序列化的一部分。只要有可能,请使用 DataContractSerializer。
我强烈建议您查看以下内容: .NET XML Serialization without 在执行任何操作之前进行文本声明。
华泰
As others mention, serialization will do the trick, but be aware of the formatters/serializer, otherwise this :
<?xml version="1.0" encoding="utf-8" ?>
will be part of your serialization. Whenever possible, use the DataContractSerializer.
I highly recommend you to see this : .NET XML Serialization without <?xml> text declaration before doing anything.
HTH
您可能需要使用 XStream 将对象存储为 XML。它非常容易使用。
You might want to use XStream to store the object as XML. It's pretty easy to use.
我建议使用 xml 序列化和反序列化。
如果我定义了一个 Person 类:
保存它/从 XML 加载它就像这样简单:
警告:这仅将类的公共属性/字段保存为 XML 元素。如果要对生成的 XML 进行附加控制,请查看 System.Xml.Serialization 命名空间(XmlAttributeAttribute 是我个人最喜欢的),
I would recommend xml serialization and deserialization.
If I have a class Person defined with:
saving it/loading it from XML is as simple as:
Caveat: This saves only the public properties/fields of a class, as XML Elements. If you want to exercise addition control over the generated XML, take a look at the attributes in the System.Xml.Serialization namespace (XmlAttributeAttribute is my personal favorite),