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 .

+7
nullable xml-serialization xml-nil
Nov 20 '08 at 21:16
source share
3 answers

I think you need the nil = "true" prefix with the namespace so that the XmlSerializer deserializes the null value.

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"/> 
+5
Nov 20 '08 at 21:49
source share

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.

+3
Oct. 16 '09 at 21:17
source share

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\""); 
0
Jan 29 '11 at 10:02
source share



All Articles