views:

1260

answers:

3

Hello all,

I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this:

<assignee-id type="integer">38628</assignee-id>

it can also look like this:

<assignee-id type="integer" nil="true"></assignee-id>

Now, in my class I have the following property that should receive the data:

[XmlElementAttribute("assignee-id")]
public int AssigneeId { get; set; }

This works fine for the first xml element example, but the second fails. I've tried changing the property type to be int? but this doesn't help. I'll need to serialize it back to that same xml format at some point too, but I'm trying to use the built in serialization support without having to resort to rolling my own.

Does anyone have experience with this kind of problem?

Thanks in advance

Andy

+1  A: 

XmlSerializer uses xsi:nil - so I expect you'd need to do custom IXmlSerializable serialization for this. Sorry.

Marc Gravell
+1  A: 

You might want to take a look at the OnDeserializedAttribute,OnSerializingAttribute, OnSerializedAttribute, and OnDeserializingAttribute to add custom logic to the serialization process

Darren Kopp
+2  A: 

It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace.

What you could do is process these with XSLT to turn this:

<assignees>
  <assignee>
    <assignee-id type="integer">123456</assignee-id>
  </assignee>
  <assignee>
    <assignee-id type="integer" nil="true"></assignee-id>
  </assignee>
</assignees>

into this:

<assignees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <assignee>
    <assignee-id xsi:type="integer">123456</assignee-id>
  </assignee>
  <assignee>
    <assignee-id xsi:type="integer" xsi:nil="true" />
  </assignee>
</assignees>

This would then be handled correctly by the XmlSerializer without needing any custom code. The XSLT for this is rather trivial, and a fun exercise. Start with one of the many "copy" XSLT samples and simply add a template for the "type" and "nil" attributes to ouput a namespaced attribute.

If you prefer you could load your XML document into memory and change the attributes but this is not a good idea as the XSLT engine is tuned for performance and can process quite large files without loading them entirely into memory.

Timothy Walters