开发者

XmlSerializer, XmlArray with dynamic content... how?

To start: This is also for REST deserialiaztion, so a custom XmlSerializer is out of the question.

I have a hjierarchy of classes that need to be serializable and deserializable from an "Envelope". It has an arrayelement named "Items" that can contain subclasses of the abstract "Item".

[XmlArray("Items")]
public Item [] Items { get; set; }

Now I need to add XmlArrayItem, but the number is not "fixed". We use so far reflection to find all subclasses with a KnownTypeProvider so it is easy to extend the assembly with new subtypes. I dont really want to hardcode all items here.

The class is defined accordingly:

[XmlRoot]
[KnownType("GetKnownTypes")]
public class Envelope {

but it does not help.

Changing Items to:

[XmlArray("Items")]
[XmlArrayItem(typeof(Item))]
public Item [] Items { get; set; }

results in:

{"The type xxx.Adjustment was not expected. Use 开发者_运维问答the XmlInclude or SoapInclude attribute to specify types that are not known statically."}

when tyrying to serialize.

Anyone an idea how I can use XmlInclude to point to a known type provider?


The KnownTypesAttribute does not work for XmlSerializer. It's only used by a DataContractSerializer. I'm quite sure that you can exchange the serializer in WCF, because I have done that for the DataContractSerializer. But if that's not an option, you have to implement IXmlSerializable yourself and handle type lookup there.

Before disqualifying this solution: You just have to implement IXmlSerializable just for a special class which replaces Item[]. Everything else can be handled by the default serializer.


According to: http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/83181d16-a048-44e5-b675-a0e8ef82f5b7/

you can use different XmlSerializer constructor:

new XmlSerializer(typeof(Base), new Type[] { typeof(Derived1), ..});

Instead of enumerating all derived classes in the base definition like this:

[System.Xml.Serialization.XmlInclude(typeof(Derived1))]
[System.Xml.Serialization.XmlInclude(typeof(Derived2))]
[System.Xml.Serialization.XmlInclude(typeof(DerivedN))]

I think you should be able to use your KnownTypeProvider to fill the array in the XmlSerializer's constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜