如何在名称不同的相同 class XmlArrayAttributes 中重新分组?

How can I regroup in a same class XmlArrayAttributes that are named differently?

我必须反序列化一个 XML 对象,该对象如下所示:

<programs>
   <item0></item0>
   <item1></item1>
    ...
   <item200></item200>
</programs>

事实是每个 <item></item> 的结构都是相同的,所以我想将所有这些项目重新组合在同一个 C# class 中,如下所示:

public class Item{
    public object prop1{get; set; }
    public object prop2{get; set; }
    public object prop3{get; set; }
}

而不是这个,现在我在 C# 中得到了这个结构:

[XmlRoot(ElementName="programs")]
public class Programs { 
    
    [XmlElement(ElementName="item0")] 
    public Item0 Item0 { get; set; } 
    
    [XmlElement(ElementName="item1")] 
    public Item1 Item1 { get; set; } 
    
    [XmlElement(ElementName="item2")] 
    public Item2 Item2 { get; set; }
    
    ...
    
    [XmlElement(ElementName="item200")] 
    public Item200 Item200 { get; set; }
}

如果有人能帮助我,我将不胜感激!

使用 LINQ,您可以将 XML 转换为所需的输出

假设给定的 xml 是这种格式

<programs>
  <item0 attribute1="0">
    <property1>test1</property1>
  </item0>
  <item1 attribute1="1">
    <property1>test2</property1>
  </item1>
  <item200 attribute1="2">
    <property1>test3</property1>
  </item200>
</programs>

有一个项目 class 具有定义的元素

public class Items
{
    public string id { get; set; }
    public string property1 { get; set; }
    public string attribute1 { get; set; }
}

使用 LINQ,您可以过滤所有项目并创建所需的对象

var xdoc = XDocument.Parse(strFile);
var result = xdoc.Descendants().Where(x=>x.Name.LocalName.StartsWith("item")).Select(y=> new Items() {
    id = y.Name.LocalName.Replace("item",""),
    property1 = y.Element("property1").Value,
    attribute1 = y.Attribute("attribute1").Value
});