从xml继承/实现List/ICollection/e.t.c反序列化类型
Posted
技术标签:
【中文标题】从xml继承/实现List/ICollection/e.t.c反序列化类型【英文标题】:Deserializing type from xml inheriting/implementing 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”节点?
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于从xml继承/实现List/ICollection/e.t.c反序列化类型的主要内容,如果未能解决你的问题,请参考以下文章
原则 2:有没有办法使用 yaml 或 xml 从 trait 继承映射?
AndroidManifest.xml中android:name功能介绍 利用自定义类继承Application 可以实现全局变量功能
AndroidManifest.xml中android:name功能介绍 利用自定义类继承Application 可以实现全局变量功能