Ignore some properties in runtime when using DataContractSerializer

扶醉桌前 提交于 2019-12-22 04:45:12

问题


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.

Thanks


回答1:


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

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

you have:

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

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

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 does not support conditional serialization of members.

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
}

or:

[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.




回答2:


There is ignore data member attribute



来源:https://stackoverflow.com/questions/10528967/ignore-some-properties-in-runtime-when-using-datacontractserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!