Search code examples
xml-serializationnullablexml-nil

Can XmlSerializer deserialize into a Nullable<int>?


I wanted to deserialize an XML message containing an element that can be marked nil="true" into a class with a property of type int?. The only way I could get it to work was to write my own NullableInt type which implements IXmlSerializable. Is there a better way to do it?

I wrote up the full problem and the way I solved it on my blog.


Solution

  • I think you need to prefix the nil="true" with a namespace in order for XmlSerializer to deserialise to null.

    MSDN on xsi:nil

    <?xml version="1.0" encoding="UTF-8"?>
    <entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="array">
      <entity>
        <id xsi:type="integer">1</id>
        <name>Foo</name>
        <parent-id xsi:type="integer" xsi:nil="true"/>