SiberianGuy
SiberianGuy

Reputation: 25312

Double serialization customization

I have the following class:

public class SomeClass
{
   public double SomeValue {get;set;}
}

I need to serialize it by XmlSerializer but I need to multiply the value by 10 during serialization and divide it by 10 during deserialization. Is there any way to implement this custom logic?

Upvotes: 2

Views: 191

Answers (4)

Paddy
Paddy

Reputation: 33867

This might be a bit hacky, but involves not serialising your main property, but providing a dummy property for the purposes of serialization that gets/sets the backing field for your main propery appropriately.

public class SomeClass 
{ 
   private double _someValue;

   [XmlIgnore()]
   public double SomeValue {
     get { return _someValue; }
     set {_someValue = value;}
   } 

   [XmlElement("SomeValue")]
   public double SomeValueSerialised
   {
      get { return _someValue * 10; }
      set { _someValue = value/10; }
   }
} 

Edit: Would note, the implementation of IXmlSerializable is probably a cleaner way to do this, but it really depends on the number of fields on your class and how lazy you're feeling...

Upvotes: 6

Amit Rai Sharma
Amit Rai Sharma

Reputation: 4225

You can control the serialization by implementing IXmlSerializable interface. Try this out..

public class SomeClass: IXmlSerializable
{
   private double someValue;
   public double SomeValue 
   {
      get{ return someValue;}
      set{ someValue = value;}
   }
   public void WriteXml (XmlWriter writer)
   {
      writer.WriteString(someValue * 10);
   }

   public void ReadXml (XmlReader reader)
   {
      someValue = Convert.ToDouble(reader.ReadString()) / 10;
    }
}

Upvotes: 0

Simon Dickson
Simon Dickson

Reputation: 711

Using the IXmlSerializable maybe

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33272

You can implement yourself IXmlSerializable:

public class SomeClass:IXmlSerializable
{
   public double SomeValue {get;set;}
 // implement here below read write as needed
 // Xml Serialization Infrastructure

public void WriteXml (XmlWriter writer)
{
    ...
}

public void ReadXml (XmlReader reader)
{
    ...
}

public XmlSchema GetSchema()
{
    return(null);
}
}

Upvotes: 0

Related Questions