1

The problem is I have a test class and a TestVariable and I would like to Serialize the Test Class without Serializing the TestVariable.:

public class TestClass
{

    public int TestVariable
    {
        get;
        set;

    }
    public int ControlVariable
    {
        get;
        set;
    }

    public TestClass()
    {
        TestVariable = 1000;
        ControlVariable = 9999;
    }
}

The Code that does the serialization:

public static void PrintClass()
{
    new XmlSerializer(typeof(TestClass)).Serialize(Console.Out, new TestClass());
}
Nick
  • 472
  • 3
  • 18
Aelphaeis
  • 2,593
  • 3
  • 24
  • 42

1 Answers1

1

Include the Namespace System.Xml.Serialization and adding the attribute [XmlIgnore] over the field or property that you want to be excluded in Serialization.

Modifying the Above code it would look like this:

public class TestClass
{

    [XmlIgnore]
    public int TestVariable
    {
        get;
        set;
    }

    public int ControlVariable
    {
        get;
        set;
    }

    public TestClass()
    {
        TestVariable = 1000;
        ControlVariable = 9999;
    }
}

This will cause TestVariable to be completely excluded from the serialization.

Aelphaeis
  • 2,593
  • 3
  • 24
  • 42
  • 1
    I find this approach inflexible, because it's defined during compile time. IMHO, [Conditional XML serialization](http://stackoverflow.com/questions/4094985/conditional-xml-serialization) using [`ShouldSerialize*`](http://msdn.microsoft.com/en-us/library/vstudio/53b8022e(v=vs.110).aspx) methods is much more flexible. – Yurii Mar 03 '14 at 14:33
  • I would have to agree that its certainly inflexible but sometimes you may not need the level of flexibility that ShouldSerialize Methods give you. In my case, I had a class where I knew at compile time that I would never need to serialize those values. So I've chosen a simple solution that gets that job done. I couldn't find a very simple solution upon searching so I posted my problem and findings so that others could benefit from it. – Aelphaeis Mar 03 '14 at 15:00