Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does XML Serialization Require Properties to be Read/Write?

I'm testing XML Serialization in my class, but i noticed that the ID number didn't get saved when i ran the program.

So i was looking around and modifying a few things but nothing worked, then i saw that all fields except ID had both get and set properties. So i added a set; property to my ID number and poof it worked. The question is, does it have to be set; and get; function on all my properties for XML Serialization to work?

I don't want the ID number to be modified after the object has been created (its automatically generated).

like image 415
Patrick Avatar asked Aug 01 '26 20:08

Patrick


2 Answers

Yes, this is basically a restriction of XML serialization. From the XML Serialization docs:

Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the BinaryFormatter class rather than XML serialization.

XML serialization isn't as flexible as one might like.

like image 169
Jon Skeet Avatar answered Aug 03 '26 10:08

Jon Skeet


Note that if you want to serialize non-public data as xml, DataContractSerializer might be useful. It isn't as flexible as XmlSerializer (and you can't specify attributes), but it can serialize non-public data:

[DataContract]
public class Person {
    [DataMember]
    private int id;

    public int Id {get {return id;}} // immutable

    public Person(int id) { this.id = id; }

    [DataMember]
    public string Name {get;set;} // mutable
}

Note also that it doesn't use your constructor... or indeed any constructor - it cheats, allowing it to create an object and fill the data in afterwards.

like image 32
Marc Gravell Avatar answered Aug 03 '26 10:08

Marc Gravell