0

I have an issue with Serializing XML. I have an object with a DateTime property where the millisecond value is 990. However when I view the outputted string it is showing like this...

<ReadingsDateTime>2016-07-04T10:10:00.99Z</ReadingsDateTime>

The code used to convert this to xml is below, what is going on, I can not find a reason that this is happening.

string xml;

try
{    
    var serializer = new XmlSerializerFactory().CreateSerializer(typeof(T), xmlNamespace);

    using (var memoryStream = new MemoryStream())
    {
        var settings = new XmlWriterSettings
        {
            Indent = false,
            NamespaceHandling = NamespaceHandling.OmitDuplicates,
            CloseOutput = false,
            WriteEndDocumentOnClose = true,
        };

        using (var xmlWriter = XmlWriter.Create(memoryStream, settings))
        {
            serializer?.Serialize(xmlWriter, obj);
        }

        memoryStream.Seek(0, SeekOrigin.Begin);

        using (var steamReader = new StreamReader(memoryStream))
        {
            xml = steamReader.ReadToEnd();
        }
    }
}
catch (Exception ex)
{
    throw new ApplicationException("Unable to convert to XML from an object", ex);
}

return xml;
Geek
  • 415
  • 4
  • 16

1 Answers1

3

.990 is the same as .99, its a fractional number so the last 0 digit is dropped. Digits have importance starting from the left hand side and going to the right. Example:

  • 1.0000 is the same value as 1
  • 2.94 is the same value as 2.940 or 2.9400 or 2.94000.

The serializer just removes the trailing 0 digits. If you want to always capture any trailing 0 digits (not sure why you would) you can add a custom string property and specify the exact output to be serialized and read in there and ignore the DateTime property, see this previous SO post as example.

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175
  • Is this a .Net specific 'thing'. The xml is created to post to an Api. If that system was Java would they treat the millisecond part as a fractional number as well? – Geek Jul 22 '16 at 10:53
  • 2
    @Hyder - its not anything specific to .net but that is just how the `XmlSerializer` serializes the fractionalal part of the millisecond value which makes sense as the trailing `0`s do not add anything of value. The result could be different depending on the serializer user and who wrote it but the string/serialized value should be able to be parsed/deserialized back to the same DateTime value either way. As far as Java I would guess it was the same but I do not know Java so could not say for sure. – Igor Jul 22 '16 at 11:01