首页 > 解决方案 > 从 xml 继承/实现 List/ICollection/等反序列化类型

问题描述

我有这样的类层次结构,我想从 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>
...

使用注释代码,它可以很好地工作,除了“And”节点没有正确反序列化并且 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)

如何正确反序列化“和”节点?

标签: c#.netxmlxml-deserialization

解决方案


尝试以下:

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

推荐阅读