Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a default value when deserializing xml in C# (.NET 3.5)?

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?

like image 445
andypike Avatar asked Dec 12 '25 04:12

andypike


2 Answers

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">
  <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.

like image 85
Timothy Walters Avatar answered Dec 14 '25 18:12

Timothy Walters


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

like image 43
Darren Kopp Avatar answered Dec 14 '25 18:12

Darren Kopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!