pee2002
pee2002

Reputation: 177

XmlSerializer one Class that has multiple classes properties

Objective: Serialize all the public properties of the ClassMain:

public class ClassMain
{
    ClassA classA = new ClassA();
    public ClassMain()
    {
        classA.Prop1 = "Prop1";
        classA.Prop2 = "Prop2";
    }

    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public ClassA ClassA
    {
        get
        {
            return classA;
        }
    }
}

ClassA:

public class ClassA
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

This is how i´m serializing:

    private void button1_Click(object sender, EventArgs e)
    {
        ClassMain classMain = new ClassMain();
        classMain.Prop1 = "Prop1";
        classMain.Prop2 = "Prop2";

        XmlSerializer mySerializer = new XmlSerializer(typeof(ClassMain));
        StreamWriter myWriter = new StreamWriter("xml1.xml");
        mySerializer.Serialize(myWriter, classMain);
        myWriter.Close();
    }

In this case, the xml output is:

<?xml version="1.0" encoding="utf-8"?>

<ClassMain xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Prop1>Prop1</Prop1>

  <Prop2>Prop2</Prop2>

</ClassMain>

As you see, is lacking the ClassA properties.

Can anyone help me out?

Regards

Upvotes: 0

Views: 258

Answers (1)

Tim Lloyd
Tim Lloyd

Reputation: 38444

Properties will only be included in Xml serialization if they have both a getter and a setter, presumably as this rule ensures that serialization can round-trip i.e. if there is no setter, you would not be able to deserialize the Xml back into the target object.

Your ClassA property has no setter.

Upvotes: 3

Related Questions