Quick Tip: How to prevent a property from #XML serialization?


Most of the cases we use XML files to serialize/de-serialize data from/to the app. To do this, we expose properties of known types and pass it to the serializer for automatic serialization process. Sometime, we don’t need to serialize all the properties and manually need to mark them from serialization process.

 

In this small blog post, we are going to see the way, by which you can prevent a property from the XML serialization process. Continue reading to know more.

 

How to prevent a property from serializing to #XML? (www.kunal-chowdhury.com)

 

The “XmlIgnoreAttribute”, part of the “System.Xml.Serialization” namespace allows you to ask the application not to serialize the marked properties. If you are serializing your data to XML, this attribute will help you. Just put the said attribute on top of all the properties, which you don’t want to serialize. The rest of the things will automatically be handle.

 

To demonstrate, just refer the below code snippet. Here the properties named TokenKey and TokenValue will not be serialize as we have marked them as XmlIgnore. Rest of the other properties will continue as-is.

public class Customer
{
    public string CustomerID { get; set; }

    public string Name { get; set; }

    public string Address { get; set; }

    [XmlIgnore]
    public string TokenKey { get; set; }

    [XmlIgnore]
    public long TokenValue { get; set; }
}

Small post, but I hope this will benefit a bunch of developers who are looking for an way to prevent some properties of their data object from serialization. Do let us know, if the information was helpful. Have a great day ahead.

 


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

1 comments

 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top