如何序列化一个没有值的整数元素?

How to serialize an integer element with no value?

我有一个 XML 元素,如下所示:

<framerate_denominator nil="true"/>

我的class会员是这样装饰的:

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

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

我的代码如下:

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

反序列化 XML 时出现以下异常:

FormatException: Input string was not in a correct format.

我不完全确定如何使用 nil="true" 属性值处理这些元素。有人有什么建议吗?

提前致谢...

当我检查一些类似的问题并回答相关问题时,我建议将 FramerateDenominator of Job class 更改为:

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

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