kevp
kevp

Reputation: 377

How to serialize an integer element with no value?

I have an XML element which looks like this:

<framerate_denominator nil="true"/>

My class member is decorated like this:

[XmlElement("framerate_denominator")]
public int? FramerateDenominator;

public bool ShouldSerializeFramerateDenominator() { return FramerateDenominator.HasValue; }

My code is as follows:

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

namespace SerializationSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            // read
            Job job = null;
            string path = @"C:\sample_job.xml";

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Job));
            using (StreamReader reader = new StreamReader(path))
            {
                //EXCEPTION HERE
                job = (Job)xmlSerializer.Deserialize(reader);
                reader.Close();
            }

            // write
            xmlSerializer = new XmlSerializer(job.GetType());
            using (StringWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, job);
                var text = textWriter.ToString();
            }
        }
    }
}

I'm getting the following exception when I deserialize the XML:

FormatException: Input string was not in a correct format.

I'm not entirely sure how I can handle these elements with the nil="true"attribute value. Does anyone have any advice?

Thanks in advance...

Upvotes: 0

Views: 1886

Answers (1)

shA.t
shA.t

Reputation: 16968

As I check some similar questions and answer about it I can suggest to change FramerateDenominator of Job class to :

[XmlElement("framerate_denominator")]
public string _FramerateDenominator { get; set; }

[XmlIgnore]
public int? FramerateDenominator
    => !string.IsNullOrEmpty(_FramerateDenominator) 
        ? (int?) int.Parse(_FramerateDenominator) 
        : null;

Upvotes: 1

Related Questions