【问题标题】:Deserializing type from xml inheriting/implementing List/ICollection/e.t.c从xml继承/实现List/ICollection/e.t.c反序列化类型
【发布时间】:2021-04-04 10:08:09
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net xml xml-deserialization


    【解决方案1】:

    尝试以下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-07
      • 2010-09-06
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多