Search code examples
c#xmldatacontractserializer

how to use DataContract to serialize a number to a percentage in the xml output?


I am wondering whether I can customize the xml output like what ToString does. e.g, use % to output 80% rather than 0.8 I also need to deserialize it later...

Thanks.


Solution

  • Don't serialize the property with the number directly. Instead, create a dummy string property that formats and parses the number:

    [DataContract]
    public class MyClass
    {
        // No DataMember attribute here
        public double MyProperty { get; set; }
    
        // Serialize this property instead
        [DataMember(Name = "MyProperty")]
        private string MyPropertyXml
        {
            get { return MyProperty.ToString("P", CultureInfo.InvariantCulture); }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    MyProperty = 0;
                }
                else
                {
                    string s = value.TrimEnd('%', ' ');
                    MyProperty = double.Parse(s, CultureInfo.InvariantCulture) / 100;
                }
            }
        }
    }
    

    It produces the following output:

    <?xml version="1.0" encoding="utf-16"?>
    <MyClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/">
      <MyProperty>42.00 %</MyProperty>
    </MyClass>