简体   繁体   English

使用混合类型的对象从XML文件生成C#类

[英]Generate C# class from XML file with mixed type of objects

I have classes like below 我有类似下面的课程

public abstract class MainDTO
{
   public string Id;
   public string CreatedBy;
}

public class SubDTO : MainDTO
{
   public string SubKey;
}

public class LockDTO : SubDTO
{
   public string LockKey;
}

I need to create a function that returns List<MainDTO> . 我需要创建一个返回List<MainDTO>的函数。 My xml file is like below. 我的xml文件如下所示。

<MainDTOList>  
  <SubDTO>
    <Id>ABC</Id>
    <CreatedBy>XXX</CreatedBy>
    <SubKey>123045</SubKey>
  </SubDTO>
  <LockDTO>
    <Id>GERTE</Id>
    <CreatedBy>VGINA</CreatedBy>
    <SubKey>123045</SubKey>
    <LockKey>L123045</SubKey>
  </LockDTO>
</MainDTOList>

I got the code to read XML file and return collection of objects when all objects are off same type by using XmlSerializer. 我得到了代码来读取XML文件,并通过使用XmlSerializer在所有对象都是相同类型时返回对象集合。 But in my case they are different. 但就我而言,他们是不同的。 Can you please let me know how to do it. 你能告诉我怎么做吗?

The simple way I can think of that you can achieve the above is to look at your XML structure, haven't use this in a bit, so forgive my small assumption mistakes 我能想到你可以实现上述的简单方法就是看看你的XML结构,有点不使用它,所以原谅我的小假设错误

The idea is to create a class that looks like your XML, if the values only apear once, the use a class that looks like this(as a sample) 我们的想法是创建一个看起来像你的XML的类,如果值只有一次,那么使用一个看起来像这样的类(作为样本)

[XmlRoot("MainDTOList")]
public class SomeClass
{
    [XmlElement("SubDTO")]
    public SubDTO SubDTO{get;set;}

    [XmlElement("SubDTO")]
    public LockDTO LockDTO{get;set;}

    ....

}

Then doing a simple XmlSerializer. 然后做一个简单的XmlSerializer。 Deserialize to deserialize your specific XML 序列以反序列化您的特定XML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM