Can an XmlSerializer deserialize to a Nullable <int>?
I would like 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 to make it work is to write your own NullableInt type, which implements IXmlSerializable . Is there a better way to do this?
I wrote a complete problem and the way I solved it on my blog .
I think you need the nil = "true" prefix with the namespace so that the XmlSerializer deserializes the null value.
<?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"/> 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 will associate this with a recursive search for child nodes, so that for any given XmlNode (or XmlDocument) I can make one call before deserializing. If you want to keep the original memory structure in unmodified memory, work with Clone () XmlNode.
An exceptionally lazy way to do this. It is fragile for a number of reasons, but my XML is simple enough to guarantee such a quick and dirty fix.
xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");