Search code examples
c#xmlserializationxmlserializer

XML File Serialization Issue


I am trying to serializing a XML file using the following code,

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

The XML file:

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

Exception : The string '' is not a valid AllXsd value.

Thanks in advance for your help.


Solution

  • I updated the code as below

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

    The above code is handling the null issue.