Ignore some properties in runtime when using DataContractSerializer
Asked Answered
M

2

8

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

Mafala answered 10/5, 2012 at 7:3 Comment(0)
L
3

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.

Logwood answered 10/5, 2012 at 7:8 Comment(2)
Thanks, Marc. So for example, if I have an instance of List<MyClass> where MyClass has three properties X, Y and Z, would it be possible to include only properties X and Y and ignore Z for each item in the list and then send this list to DataContractSerializer and serializer will include only X and Y in the output and ignore Z? I just want to exclude some properties for every item in the list. Is that possible with some of the options you've specified above?Mafala
In the case of wanting to serialize X and Y but not Z; with DCS that is only available (as far as I know) if it applies to all the items, i.e. by choosing [DataMember] or [IgnoreDataMember] appropriately; DCS does not have conditional serialization to the best of my knowledgeLogwood
C
1

There is ignore data member attribute

Conferral answered 10/5, 2012 at 7:12 Comment(1)
That is compile-time, not run-time, and cannot apply to individual list items.Logwood

© 2022 - 2024 — McMap. All rights reserved.