如何仅从日期时间序列化XML数据在C# [英] How to serialize Xml Date only from DateTime in C#

查看:1424
本文介绍了如何仅从日期时间序列化XML数据在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的类;

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

然后我用连载我的对象到XML;

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)
{
    ....
}

我的问题是返回的XML当DATEOFBIRTH格式是这样2012-11-14T00:00:00,而不是2012年11月14日

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 ?

推荐答案

您应该使用的 XmlElementAttribute.DataType 属性并指定 日期

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;}
}

使用此输出

<?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> 



另一种选择是使用字符串属性只是序列化(由你使用的DateTime 属性支持),作为的强制XmlSerializer的序列化日期时间为'YYYY-MM-DD HH:MM:SS'(这需要对的DataContractSerializer ,其中 XS:日期类型不同时支持)

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)

这篇关于如何仅从日期时间序列化XML数据在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆