微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从继承/实现 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>
...

使用注释代码,它运行良好,除了“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 location)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type,XmlAttributeOverrides overrides,Type[] extraTypes,XmlRootAttribute root,Type[] extraTypes)

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

解决方法

尝试以下操作:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。