Silverlight 4 中的 Xml 序列化
假设我有以下类:
public class Entity { ... }
public class MyEntity : Entity
{
}
MyEntity 可以是复杂对象,它具有实体列表作为其属性。 我想将 MyEntity 序列化为 xml,但仅限基类的属性,即实体对象。 我尝试将 DataContractSerializer 与 DataMemberAttribute 一起使用,但似乎开始 在 .NET 3.5 中,即使未应用 DataMemberAttribute,它也会序列化所有公共属性。
我有什么选择?
Let say I have following classes:
public class Entity { ... }
public class MyEntity : Entity
{
}
MyEntity can be complex object, which has list of Entity as its property.
I'd like to serialize MyEntity to xml, but only properties of base class, i.e Entity object.
I tried to use DataContractSerializer with DataMemberAttribute, but it seems, starting
with .NET 3.5 it serializes all public properties even if DataMemberAttribute is not applied.
What are my options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,回答我自己的问题。我当前的解决方案是在基类(Entity 类)中实现 IXmlSerializable,而不为派生类(MyEntity)实现此接口。然后,XmlSerializer 仅序列化基类的公共属性。棘手的部分是实现 IXmlSerialized;特别是 ReadXml() 方法。 Paul Alexander 在以下帖子中的回答(未选择的答案!)对我有帮助:
在 C# 中使用 XmlReader 读取 Xml
Okay, answer to my own question. My current solution is to implement IXmlSerializable in the base class (Entity class), and not implement this interface for derived classes (MyEntity). Then XmlSerializer serializes public properties of only the base class. Tricky part is implementing IXmlSerializable; especially ReadXml() method. An answer by Paul Alexander (not selected answer!) in the following post was helpful to me:
Reading Xml with XmlReader in C#