从继承/实现List/ICollection/e.t.c的xml反序列化类型



我有这样的类层次结构,我想从XML反序列化它。这个层次结构将用";OrCondition:ConditionToWork";,因此,解决方案必须是可扩展的

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>{}

使用这些类的类型看起来像

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

以及我想要反序列化的XML:

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

使用带注释的代码,它可以很好地工作;并且";节点未正确反序列化,AndCondition实体未添加到Worker.Conditions中。但是在取消对XmlArrayItem(typeof(AndCondition((的注释时。我得到以下异常";System.PlatformNotSupportedException:"不支持编译JScript/CSharp脚本">

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)

如何反序列化";并且";节点是否正确?

尝试以下操作:

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:temptest.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; }
}
}

最新更新