Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Xml Date only from DateTime in C#

I've the following simple class;

Birthdays
{
  public DateTime DateOfBirth {get;set;}
  public string Name {get;set;}
}

I then serialise my object to Xml using;

try
{
   XmlSerializer serializer = new XmlSerializer(obj.GetType());

   using (MemoryStream ms = new MemoryStream())
   {
        XmlDocument xmlDoc = new XmlDocument();

        serializer.Serialize(ms, obj);
        ms.Position = 0;
        xmlDoc.Load(ms);
        return xmlDoc;
    }
}
catch (Exception e)
{
    ....
}

The problem I have is that when the Xml is returned the DateOfBirth format is like 2012-11-14T00:00:00 and not 2012-11-14.

How can I override it so that I'm only returning the date part ?

like image 361
neildt Avatar asked Nov 14 '13 16:11

neildt


People also ask

How to serialize data in XML?

To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization. The central class in XML serialization is the XmlSerializer class, and the most important methods in this class are the Serialize and Deserialize methods.

Can you serialize DateTime?

For serializing, you can use the DateTime(Offset). ToString method in your converter write logic. This method allows you to write DateTime and DateTimeOffset values using any of the standard date and time formats, and the custom date and time formats.

What is serializing XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is XML serialization in c#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.


1 Answers

You should use the XmlElementAttribute.DataType property and specify date.

public class Birthdays
{
  [XmlElement(DataType="date")]
  public DateTime DateOfBirth {get;set;}
  public string Name {get;set;}
}

Using this outputs

<?xml version="1.0" encoding="utf-16"?>
<Birthdays xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DateOfBirth>2013-11-14</DateOfBirth>
  <Name>John Smith</Name>
</Birthdays> 

Another option is to use a string property just for serialization (backed by a DateTime property you use), as at Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss' (this is needed for DataContractSerializer, where the xs:date type is not as well-supported)

like image 177
Tim S. Avatar answered Nov 11 '22 04:11

Tim S.