Deukalion
Deukalion

Reputation: 2655

XmlSerialization - Ignore variables by default

Is it possible to ignore normal variables by default when serializing objects to xml with XmlSerialization?

I have a variable:

class SomeClass
{
    private bool trueOrFalse = false;

    public bool TrueOrFalse
    {
        get { return trueOrFalse; }
        set { trueOrFalse = value; }
    }
}

when serializing this, I get two "elements" in the XML file one for each - but they're the same. So for a cleaner XML file I wish just to include Properties somehow, and without having to use XmlIgnore - just as a default, any way to do this?

Upvotes: 1

Views: 946

Answers (3)

Deukalion
Deukalion

Reputation: 2655

Sorry, it was my mistake. I have an interface that a couple of classes implements and all the fields are set to private. With my luck by testing a specific object that implement the interface I set it's field to public which was the cause of it writing both the propertyname + propertyvalue and the field and fieldvalue.

So, fields has to be private.

Upvotes: 2

Nudier Mena
Nudier Mena

Reputation: 3274

As @Jaime Olivares said in xml serialization only serialize the public members in a class, try to prefix your field like this

[Serializable]
class SomeClass
{
//does not persist the member in your serialization process
 [NonSerialized]
 private bool trueOrFalse = false;

 public bool TrueOrFalse
 {
    get { return trueOrFalse; }
    set { trueOrFalse = value; }
 }

}

Upvotes: -1

Steve Wellens
Steve Wellens

Reputation: 20620

Depending on the version of C#, you may be able to define the property like this:

public class SomeClass
{
    public bool TrueOrFalse{ get; set; }      
}

Upvotes: 0

Related Questions