Search code examples
c#xml-serializationxml-deserialization

Deserializing an XML into a object: XML element with xsi:nil="true" should have null value (and not empty value) for respective property in object


When de-serializing the below XML into Parent class, ElementTwo and ElementThree are empty strings, which is expected. But ElementOne should have been null but instead this is also empty string.

What does i:nil="true" mean?

XML

<?xml version = \"1.0\" ?>
<Parent
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ElementOne xsi:nil="true"/>
<ElementTwo></ElementTwo>
<ElementThree />
<ElementFour>Value</ElementFour>
</Parent>

C# Class

public class Parent
{
    public string ElementOne { get; set; }
    public string ElementTwo { get; set; }
    public string ElementThree { get; set; }
    public string ElementFour { get; set; }
}

When de-serializing the XML into an object, the XML element with xsi:nil="true" is not being converted as null. Instead, it is assigned as empty string. But I've a requirement where it should be converted as null only. Please help me to figure out a solution or point put where I went wrong

I've given the sample used in below fiddle link:

https://dotnetfiddle.net/VfNJYv


Solution

  • Put

    [XmlElement(IsNullable=true)] 
    

    above the Public string ElementOne get/set property

    .NET fiddle