Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 227
Bairavi Navaradian Avatar asked Jan 30 '26 20:01

Bairavi Navaradian


1 Answers

Put

[XmlElement(IsNullable=true)] 

above the Public string ElementOne get/set property

.NET fiddle

like image 195
Putta Boo Avatar answered Feb 01 '26 12:02

Putta Boo



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!