问题描述
无法将 datetime.now 值传递给节点createddatetime".输出 xml 文件丢弃该节点.我使用了以下代码,
Unable to pass datetime.now value to a node 'createddatetime'.Output xml file discards the node. i used the following code,
string PATH = "C:\\Samplex.xml";
CreateEmptyFile(PATH);
var data = new AutoCount();
data.Product = "AutoCount Accounting";
data.Version = "1.5";
data.CreatedApplication = "BApp";
data.CreatedBy = "Business Solutions";
data.CreatedDateTime = DateTime.Now; /* this line*/
var serializer = new XmlSerializer(typeof(AutoCount));
using (var stream = new StreamWriter(PATH))
serializer.Serialize(stream, data);
结果是:
<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
<Product>AutoCount Accounting</Product>
<Version>1.5</Version>
<CreatedApplication>BApp</CreatedApplication>
<CreatedBy>Business Solutions</CreatedBy>
</AutoCount>
代替:
<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
<Product>AutoCount Accounting</Product>
<Version>1.5</Version>
<CreatedApplication>BApp</CreatedApplication>
<CreatedBy>Business Solutions</CreatedBy>
<CreatedDateTime>2015-05-03 18:01:35</CreatedDateTime>
</AutoCount>
推荐答案
当 xsd.exe 为可选元素(例如带有 minOccurs="0"
的元素)生成类定义时对于映射到值类型(例如 DateTime
)的类型,将生成一个附加属性以指示是否应序列化其值.
When a class definition is generated by xsd.exe for an optional element (one with minOccurs="0"
, for example) with a type that maps to a value type such as DateTime
, an additional property will be generated to indicate whether or not its value should be serialized.
在这种情况下,CreatedDateTime
似乎是可选的,因此相关的 CreatedDateTimeSpecified
属性应设置为 true
:
In this case it would seem CreatedDateTime
is optional, so the related CreatedDateTimeSpecified
property should be set to true
:
data.CreatedDateTime = DateTime.Now;
data.CreatedDateTimeSpecified = true;
这篇关于通过 c# 在 XML 中不接受日期时间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!