Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
Alex Zel Avatar asked Mar 23 '26 23:03

Alex Zel


1 Answers

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'/>
like image 188
Akshey Bhat Avatar answered Mar 25 '26 13:03

Akshey Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!