XmlSerializer - Serialize properties with get accessors?

P

Peter Cresswell

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
(e-mail address removed)
 
W

William Stacey [MVP]

Has to be read/write. Says in the docs. Could not deserialize if no set
accessor.
 
G

Guest

From what I know, you have 2 options:

1. Implement set accessors that do nothing (not very pretty I know):

public int Two
{
get { return 1+1;}
set { }
}

2. Implement IXmlSerializable, which is not currently intended for developer use, but this is being changed in 2.0. This interface allows you to control exactly how your objects are serialized/deserialized through 3 methods - ReadXml, WriteXml and GetSchema.

Hope this helps
Dan
 
W

William Stacey [MVP]

The other one is create simple xml "doc" classes that only have public
fields with any xml attributes you need. That way you not messing with
these kind of issues with your app classes. Create a method in your real
class to "clone" your object to its' xml class and serialize that class
instead, etc.

--
William Stacey, MVP

Dan Kelley said:
From what I know, you have 2 options:

1. Implement set accessors that do nothing (not very pretty I know):

public int Two
{
get { return 1+1;}
set { }
}

2. Implement IXmlSerializable, which is not currently intended for
developer use, but this is being changed in 2.0. This interface allows you
to control exactly how your objects are serialized/deserialized through 3
methods - ReadXml, WriteXml and GetSchema.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top