How to serialize Xml Date only from DateTime in C#

12,622

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)

Share:
12,622
neildt
Author by

neildt

An enthusiastic IT professional, coming from a Classic ASP background. Currently programming with Visual Studio in C# .NET, Web Services (XSMX and Wcf), MS SQL Server, MySQL, and IIS 8.5. Interested in learning new technologies, design patterns and exciting career opportunities.

Updated on July 22, 2022

Comments

  • neildt
    neildt almost 2 years

    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 ?

  • Ole Albers
    Ole Albers over 10 years
    (second part:) Would cut off any existing time, but still "dateTime" has the 00:00 Time. Would not change a thing.
  • terrybozzio
    terrybozzio over 10 years
    thats why i commented use datetime.Date.
  • Ole Albers
    Ole Albers over 10 years
    But still: The xml would look just like before
  • terrybozzio
    terrybozzio over 10 years
    if the problem is in wants serialized then not mine not yours but tim S.(for a single property result i mean).my answer is to not rewrite the class(although it is the best solution),and just "get" the desired formatt.
  • Ole Albers
    Ole Albers over 10 years
    better than my answer I have to admit :)
  • Chuck Savage
    Chuck Savage over 3 years
    Helped me get there for XElement save of just the date, thanks.