我有一些XML,其中包含两个general
元素,每个元素包含不同的信息。例如:
<overview>
<general> <!-- General 01 -->
<datetime></datetime>
<location></location>
</general>
<instance>
<general> <!-- General 02 -->
<instanceid></instanceid>
<instancetype></instancetype>
</general>
</instance>
<instance>
....
</instance>
</overview>
通过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; }
}
是否可以为这些general
元素创建两个不同的类(因为它们各自包含不同的信息),并指定应使用哪个类?例如:
[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; }
}
答案 0 :(得分:2)
为了达到目标,您已经关闭,需要为每个属性分配适当的类类型,例如
[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; }
}