0

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...

kevp
  • 377
  • 2
  • 7
  • 23
  • 1
    As `XmlSerializer` will make null a property that is not present in the xml, I can suggest you to skip those tags as suggested [here](https://stackoverflow.com/a/2966688/4519059) ;). – shA.t Aug 21 '17 at 05:41
  • 1
    For `nil` to be supported, it would need to be in the `xsi` namespace. See [the docs](https://msdn.microsoft.com/en-us/library/ybce7f69(v=vs.100).aspx). If it's as you've described, you would have to handle this explicitly yourself. – Charles Mager Aug 21 '17 at 10:10
  • @shA.t I currently have a hacky implementation of the suggestion there. I'm yanking out empty node values from the XDocument using Linq. Seems to do the trick, but I think that your answer below is more what I'll end up implementing. – kevp Aug 22 '17 at 16:12

1 Answers1

1

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;
shA.t
  • 16,580
  • 5
  • 54
  • 111
  • That's interesting - you can define an anonymous function to clean up values. I'll try this tonight, thanks. – kevp Aug 22 '17 at 16:10