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

痴心易碎 提交于 2019-12-23 16:26:31

问题


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?


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/193185/is-it-possible-to-set-a-default-value-when-deserializing-xml-in-c-sharp-net-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!