Search code examples
c#xmlserialization

Xml Empty Tag Deserialization


Could you please help me to find the solution to deserialize xml file which contains an empty tag?

Example is here:

<Report>
    <ItemsCount></ItemsCount>
</Report>

And I want to deserialize it into object of class like:

public class Report{
    public int? ItemsCount { get;set;}
}

my xml schema which i'm using in deserialization is:

[XmlRoot]
public partial class Report
{
   private int? itemsCount;

   [XmlElement(IsNullable = true)]
   public int? ItemsCount {
      get
      {
           return itemsCount;
      }
      set
      {
           itemsCount = value;
      }
}

It works well if the ItemsCount tag is missing at all, but if it is exist and is empty at the same moment, in that case it throwing the exception regarding lines there this tag is located in xml.

I saw a lot of links here while trying to find the solution, but without success.

And also, i don't want to just ignore the tag for all the cases, i want to get a null value instead then it is empty.


Solution

  • XmlSerializer is trying to convert string.Empty value of tag to integer and failing. Change your property as below to convert data type to string:

    [XmlElement]
    public string ItemsCount {
          get
          {
               return itemsCount;
          }
          set
          {
               itemsCount = value;
          }
    }
    

    This will set property Itemscount to empty in the above case. For null value for the above property the xml should be as below:

    <ItemsCount xs:Nil='true'/>