Ignore some properties at run time when using DataContractSerializer

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

For example, so that the user can select the desired xml elements in a list control, and then serialize only those elements that are selected by the user, with the exception of all that are not selected.

thanks

+7
source share
2 answers

For a list script, there may simply be another property, so instead:

[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 , which would be painful, since your list would have to load in Items; if you need to also deserialize, you may need to write a complex user list.


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

 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 an XmlSerializer , although for a property, say, Foo , you simply 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 */ } } 

They are used solely as a name-based agreement.

+3
source
+1
source

All Articles