The XMLIgnore attribute is used to tell the XmlSerializer that this field is transient, and should not be (de)serialized. The most typical use for this would be to mark calculated fields with this attribute. This is an easy customization that helps your serialization process, but it leaves a bit to be desired. It's an "all or nothing" approach, where the property is either streamed or not.
This MSDN article hints at what to do to get more fine-grained control of this aspect of serialization. Basically, you create a public boolean field or property named propertyNameSpecified for the property you want to control. The XmlSerializer uses this convention to determine whether or not to include the associated property for serialization. Since this new Specified field will be eligible for serialization, be sure to mark it with the XmlIgnore attribute to prevent it from being serialized.
A very simple code listing showing how this all fits together:
public class Player { private int number; private string name; [XmlElement("jerseyNumber")] public int Number { get { return number; } // You could add more logic here to only set NumberSpecified based on some criteria set { number = value; NumberSpecified = true; } } [XmlElement("playerName")] public string Name { get { return name; } set { name = value; } } [XmlIgnore] public bool NumberSpecified; } The downsides to using this techniques are:
public class Player
{
private int number;
private string name;
[XmlElement("jerseyNumber")]
public int Number
get { return number; }
// You could add more logic here to only set NumberSpecified based on some criteria
set { number = value; NumberSpecified = true; }
}
[XmlElement("playerName")]
public string Name
get { return name; }
set { name = value; }
[XmlIgnore]
public bool NumberSpecified;
Download the very simple sample showing this behavior here.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.