Deserializing type from xml inheriting/implementing List/ICollection/e.t.c

Viewed 106

I has such hierarchy of classes, which i want to deserialize from XML. This hierarchy will be extended with "OrCondition:ConditionToWork", e.t.c.. So solution must be extensible

public abstract class ConditionToWork { }

[XmlType(nameof(WorkerMethodCondition))]
public class WorkerMethodCondition : ConditionToWork
{
    [XmlAttribute(nameof(WorkerMethodName))]
    public string WorkerMethodName { get; set; };
}

[XmlType("And")]
public class AndCondition : List<ConditionToWork>{}

Type using these classes looks like

[XmlType("Worker")]
public class Worker
{
    [XmlArrayItem(typeof(WorkerMethodCondition))/*, XmlArrayItem(typeof(AndCondition))*/]
    public AndCondition Conditions { get; set; }
}

And XML which i want to deserialize:

...
<Worker>
  <Conditions>
    <WorkerMethodCondition/>
    <WorkerMethodCondition/>
    <WorkerMethodCondition/>
    <And>
      <WorkerMethodCondition/>
    </And>
  </Conditions>
</Worker>
...

With commented code it works nicely except "And" nodes is not deserialized properly and AndCondition entity is not added to Worker.Conditions. But when uncomment XmlArrayItem(typeof(AndCondition)). I get following exception "System.PlatformNotSupportedException: 'Compiling JScript/CSharp scripts is not supported'"

at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location)
   at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace, String location)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, Type[] extraTypes)

How to deserialize "And" nodes properly?

1 Answers

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(Worker));
            Worker worker = (Worker)serializer.Deserialize(reader);
        }
    }
    public class Worker
    {
        public Conditions Conditions { get; set; }
    }
    public class Conditions
    {
        [XmlElement()]
        public List<string> WorkerMethodCondition { get; set; }
        public And And { get; set; }
    }
    public class And
    {
        public string WorkerMethodCondition { get; set; }
    }
}
Related