How do I Selectively Serialize Fields and Properties using XmlSerializer

StackOverflow https://stackoverflow.com/questions/22149061

  •  19-10-2022
  •  | 
  •  

سؤال

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());
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top