简体   繁体   中英

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 ?

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)

Try this example out:

        string date = "2012-11-14T00:00:00";

        string result = DateTime.Parse(date).ToShortDateString();

        //or....

        DateTime dateTime = new DateTime();

        dateTime = DateTime.Parse(date);
        //now its only use dateTime.Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM