【问题标题】:XML File Serialization IssueXML 文件序列化问题
【发布时间】:2020-05-14 10:19:30
【问题描述】:

我正在尝试使用以下代码序列化 XML 文件,

using System;
using System.Xml;
using System.Xml.Serialization;

namespace TestXML
{
    [Serializable]
    [XmlRootAttribute("Test")]
    public class Test100
    {
        [XmlElementAttribute("StartDate")]
        public DateTime StartDate { get; set; }

        [XmlElementAttribute("EndDate")]
        public DateTime EndDate { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test100 obj = new Test100();
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Test100));
                XmlReader reader = XmlReader.Create(@"C:\MyProjects\TestXML\TestXML\Test.xml");
                obj = (Test100)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

XML 文件:

<?xml version="1.0"?>
<Test>
    <StartDate>2020-01-19T00:00:00Z</StartDate>
    <EndDate></EndDate>
</Test>

例外:字符串 '' 不是有效的 AllXsd 值。

提前感谢您的帮助。

【问题讨论】:

标签: c# xml serialization xmlserializer


【解决方案1】:

我更新了如下代码

public string EndDate { get; set; }

[XmlIgnore]
public bool? _EndDate
{
    get
    {
        if (!string.IsNullOrWhiteSpace(EndDate))
        {
           return bool.Parse(EndDate);
        }
           return null;
    }
}

以上代码正在处理 null 问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2012-03-27
    相关资源
    最近更新 更多