[英]Deserialize different xml elements with same name into different C# classes
I have some XML which contains two general
elements, each containing different information. 我有一些XML,其中包含两个general
元素,每个元素包含不同的信息。 For example: 例如:
<overview>
<general> <!-- General 01 -->
<datetime></datetime>
<location></location>
</general>
<instance>
<general> <!-- General 02 -->
<instanceid></instanceid>
<instancetype></instancetype>
</general>
</instance>
<instance>
....
</instance>
</overview>
After running this XML through Xml2CSharp.com , the information in both different general
elements are combined into one class, for example: 通过Xml2CSharp.com运行此XML后,两个不同的general
元素中的信息都组合到一个类中,例如:
[XmlRoot(ElementName="general")]
public class General {
[XmlElement(ElementName="datetime")]
public string Datetime { get; set; }
[XmlElement(ElementName="location")]
public string Location { get; set; }
[XmlElement(ElementName="instanceid")]
public string Instanceid { get; set; }
[XmlElement(ElementName="instancetype")]
public string Instancetype { get; set; }
}
Is it possible to create two different classes for these general
elements (since they each contain different information), and specify which should be used? 是否可以为这些general
元素创建两个不同的类(因为它们每个都包含不同的信息),并指定应使用哪个类? For example: 例如:
[XmlRoot(ElementName="overview/general")]
public class OverviewGeneral {
[XmlElement(ElementName="datetime")]
public string Datetime { get; set; }
[XmlElement(ElementName="location")]
public string Location { get; set; }
}
[XmlRoot(ElementName="instance/general")]
public class InstanceGeneral {
[XmlElement(ElementName="instanceid")]
public string Instanceid { get; set; }
[XmlElement(ElementName="instancetype")]
public string Instancetype { get; set; }
}
You are closed to achieve your result, you need to assign proper class type to each property like 您已关闭以实现结果,您需要为每个属性分配适当的类类型,例如
[XmlRoot(ElementName = "instance")]
public class Instance
{
[XmlElement(ElementName = "general")]
public InstanceGeneral General { get; set; } //<= InstanceGeneral Use Here
}
[XmlRoot(ElementName = "overview")]
public class Overview
{
[XmlElement(ElementName = "general")]
public OverviewGeneral General { get; set; } //<= OverviewGeneral Use Here
[XmlElement(ElementName = "instance")]
public Instance Instance { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.