Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 262
Alex Scordellis Avatar asked Nov 20 '08 21:11

Alex Scordellis


People also ask

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.

What is XML deserialize?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


2 Answers

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"/>
like image 138
Phil Jenkins Avatar answered Oct 02 '22 20:10

Phil Jenkins


My fix is to pre-process the nodes, fixing any "nil" attributes:

public static void FixNilAttributeName(this XmlNode @this)
{
    XmlAttribute nilAttribute = @this.Attributes["nil"];
    if (nilAttribute == null)
    {
        return;
    }

    XmlAttribute newNil = @this.OwnerDocument.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
    newNil.Value = nilAttribute.Value;
    @this.Attributes.Remove(nilAttribute);
    @this.Attributes.Append(newNil);
}

I couple this with a recursive search for child nodes, so that for any given XmlNode (or XmlDocument), I can issue a single call before deserialization. If you want to keep the original in-memory structure unmodified, work with a Clone() of the XmlNode.

like image 40
Tom Mayfield Avatar answered Oct 02 '22 20:10

Tom Mayfield