本文介绍了使用 DataContractSerializer 时忽略运行时的某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DataContractSerializer 使用 DataMember 属性将对象序列化为 XML(仅序列化公共属性).
是否可以动态忽略某些属性,以便它们不会包含在 XML 输出中?

例如,允许用户在某些列表控件中选择所需的 xml 元素,然后仅序列化用户选择的那些元素,排除所有未选择的元素.

I am using DataContractSerializer to serialize an object to XML using DataMember attribute (only public properties are serialized).
Is it possible to dynamically ignore some properties so that they won't be included in the XML output?

For example, to allow user to select desired xml elements in some list control and then to serialize only those elements user selected excluding all that are not selected.

谢谢

推荐答案

对于列表场景,也许只是有不同的属性,所以代替:

For the list scenario, maybe just have a different property, so instead of:

[DataMember]
public List<Whatever> Items {get {...}}

你有:

public List<Whatever> Items {get {...}}

[DataMember]
public List<Whatever> SelectedItems {
   get { return Items.FindAll(x => x.IsSelected); }

但是,反序列化会很痛苦,因为您的列表需要输入到 Items 中;如果您还需要反序列化,则可能需要编写一个复杂的自定义列表.

however, deserializing that would be a pain, as your list would need to feed into Items; if you need to deserialize too, you might need to write a complex custom list.

作为第二个想法;只需使用要序列化的项目创建对象的第二个实例;非常简单有效:

As a second idea; simply create a second instance of the object with just the items you want to serialize; very simple and effective:

var dto = new YourType { X = orig.X, Y = orig.Y, ... };
foreach(var item in orig.Items) {
    if(orig.Items.IsSelected) dto.Items.Add(item);
}
// now serialize `dto`

AFAIK,DataContractSerializer 不支持成员的条件序列化.


AFAIK, DataContractSerializer does not support conditional serialization of members.

个人属性级别,如果您使用XmlSerializer,这一个选项,但是 - 对于属性,例如,Foo,你只需添加:

At the individual property level, this is an option if you are using XmlSerializer, though - for a property, say, Foo, you just add:

public bool ShouldSerializeFoo() {
    // return true to serialize, false to ignore
}

或:

[XmlIgnore]
public bool FooSpecified {
    get { /* return true to serialize, false to ignore */ }
    set { /* is passed true if found in the content */ }
}

这些纯粹是作为基于名称的约定而应用的.

These are applied purely as a name-based convention.

这篇关于使用 DataContractSerializer 时忽略运行时的某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:03
查看更多