C# 您可以为日期时间的 XmlSerialization 指定格式吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1118833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you specify format for XmlSerialization of a datetime?
提问by cjk
I need to serialize / deserialize a datetime into yyyyMMdd format for an XML file. Is there an attribute / workaround I can use for this?
我需要将日期时间序列化/反序列化为 XML 文件的 yyyyMMdd 格式。是否有我可以使用的属性/解决方法?
采纳答案by John Saunders
No, there isn't. If it's in that format, then it's not a valid dateTime as far as XML Schema is concerned.
不,没有。如果它是那种格式,那么就 XML Schema 而言,它不是有效的 dateTime。
The best you can do is as follows:
您可以做的最好的事情如下:
[XmlIgnore]
public DateTime DoNotSerialize {get;set;}
public string ProxyDateTime {
get {return DoNotSerialize.ToString("yyyyMMdd");}
set {DoNotSerialize = DateTime.Parse(value);}
}
回答by th2tran
XmlElementAttribute#DataType should provide what you need:
XmlElementAttribute#DataType 应该提供你需要的:
[XmlElement(DataType="date")]
public DateTime Date1 {get;set;}
This will get Date1property serialized to the proper xml dateformat.
这会将Date1属性序列化为正确的xml 日期格式。