Groups | Blog | Home
all groups > dotnet xml > july 2004 >

dotnet xml : XmlSerializer - Serialize properties with get accessors?


Peter Cresswell
7/22/2004 8:56:17 PM
Hello everyone,

I would like to serialize an object to XML. Currently my code will serialize
all of the public properties that are value types, but not my public
properties that have get accessors. e.g:

public class MyObject
{
public string name; // This is serialized OK

public int Two
{
get { return 1+1;} // This does not serialize
}

}

Is it possible to serialize these properties too? If so could you please
tell me how (or point me in the direction of a doc that explains it).
I'm fairly new to working with the Xml parts of the framework so I'm sorry
if I've missed something obvious.

Thanks very much!

Peter Cresswell
p-cresswell@iname.com

Peter Cresswell
7/23/2004 2:32:02 AM
Emil,

I wasn't interested in deserializing the object, which is why I left out the set accessor.

I added the set accessor as you suggested and it works perfectly!

Thank you!!!!!

Peter

[quoted text, click to view]
Emil Kvarnhammar
7/23/2004 9:38:22 AM
Hi Peter!

Read the MSDN documentation of XmlSerializer.
The XmlSerializer processes all public fields AND public properties by
default.

The reason why your property (named Two) is not serialized, is that your'e
missing a setter. Look at the code below, which will make the property to
serialize.

(Normally you use properties to wrap a private field, which then also needs
a set)

Without a "set", your property does not support serialization (or rather, it
wouldnt
be possible to deserialize xml to this object).

/Emil Kvarnhammar

[quoted text, click to view]

Emil Kvarnhammar
7/23/2004 10:44:46 AM
Oups,

I forgot the example code.

// example property that can be serialized.
public int Two
{
get{return 1+1;}
set{}
}

// end of code
[quoted text, click to view]

AddThis Social Bookmark Button