In most 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 them to the serializer for the automatic serialization process. Sometimes, we don’t need to serialize all the properties and manually need to mark them from the 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 to the below code snippet. Here the properties named TokenKey and TokenValue will not be serialized as we have marked them as XmlIgnore. The 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 a 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.

 

 


Kunal Chowdhury

About the Author

Solution Architect & Former Microsoft MVP

Kunal Chowdhury is an enterprise solution architect and former multi-year Microsoft MVP. He is the author of three technical books: Windows Presentation Foundation Development Cookbook, Mastering Visual Studio 2017, and the Mastering Visual Studio 2019.

He publishes technical and non-technical articles on .