Serialisation auto formatting

M

McGiv

Hi,
I'm trying to serialise some objects and I've can't get the built in
serialisation to output exactly what I want. For the moment I'm
implementing the IXmlSerializable interface and doing it the long way.
For future reference is it possible to specify how a property should
be formatted when being serialised?

Example:

In the following code I want the Time property to be formatted not to
the default .ToString() but to .ToUniversalTime().ToString("r")

[Serializable]
public class Test
{

[XmlElement("time")]
public DateTime Time;
}

I was wondering is there an attribute that I can add along with
XmlElement to do this?

Perhaps something link:


[XmlElement("time"), XmlFormat(formatDate)]
public DateTime Time;


void FormatDate(object obj, XmlWriter writer)
{
DateTime dt = (DateTime)obj;
writer.WriteString( dt.ToUniversalTime().ToString("r") );
}

Where xmlformat created a delegate of type:

public delegate void XmlPropertyFormatter(object obj, XmlWriter
writer);

and when the Time property is to be serialised it calls the delegate
passing the Time property as the object parameter and the XmlWriter.


Cheers
Damien
 
S

Sherif ElMetainy

Hello

The default serialization doesn't call the default ToString method, because
it is culture dependent and can differ from one machine to another.
The default serilization is in the format
yyyy'-'MM'-'ss'T'HH':'mm':'ss'.'ffffffzzz
Below is a piece of code that serializes the object the way you want. I made
the Time field ignored, and made a string property that returns the desired
format.Note that after formatting a date to string you have a string object
to serialize not a date object.


public class Test
{
[XmlElement("time")]
public string TimeString
{
get
{
return Time.ToUniversalTime().ToString("r");
}
set
{
Time = DateTime.ParseExact(value, "r",
System.Globalization.CultureInfo.InvariantCulture);
}
}
[XmlIgnore]
public DateTime Time;
}

Best regards,
Sherif
 

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