Search code examples
c#xmlserializer

XmlSerializer ignore public fields?


I am using some existing code that is defined as follows.

class Example
{
    public float x_field;
    public float x_property
    {
        get { return x_field; }
        set { x_field = value; }
    }
}

Why its defined like this I don't know, but I'm unable to change its implementation. The problem, is that when I serialize it, I obviously get both values in the xml output. How can I stop this from occurring if I can't modify the 'Example' class?

I want the Serializer to only output public properties and not public fields.


Solution

  • You could use the XmlAttributeOverride parameter of XmlSerializer e.g.

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attributes = new XmlAttributes();
    attributes.XmlIgnore = true;
    overrides.Add(typeof(Example), "x_field", attributes);
    
    XmlSerializer xs = new XmlSerializer(typeof(Example), overrides);