Skip to main content
 首页 » 编程设计

c#之如何将具有不同名称的xml节点反序列化为列表

2024年02月20日26cmt

我想使用 C# 反序列化一个 xml 文件。

文件有这样的形式:

<parent> 
   <TotProd Name="Total Produce Kwh"> 
       <Time value="00:00:00">10</Time> 
       <Time value="00:30:00">10</Time> 
        ............  
   </TotProd> 
   <ProdToNet Name="Produce to Net (iec)"> 
       <Time value="00:00:00">10</Time> 
       <Time value="00:30:00">10</Time> 
        ........... 
   </ProdToNet> ..... 
</parent> 

我想反序列化 parent 的所有子元素进入 List<Myclass>与 TotProd/ProdToNet作为 Myclass 的属性(property).

我该怎么做。

请您参考如下方法:

如果它们具有相同的结构,您可以为两个元素使用公共(public)类:

public class Time{ 
    [XmlAttribute] 
    public string value {get; set; } 
    [XmlText] 
    public string Text {get;set;} // this will hold the innerText value ("10") of <Time> 
} 
 
public class Prod{ 
 
    [XmlAttribute] 
    public string Name {get; set; } 
    [XmlElement("Time")] 
    public List<Time> Time {get; set; } 
} 
 
[XmlRoot("parent")] 
public class Parent{ 
    [XmlElement(ElementName="ProdToNet", Type=typeof(Prod))] 
    [XmlElement(ElementName="TotProd", Type=typeof(Prod))] 
    public List<Prod> {get; set;} 
} 

更新: Time:value 看起来像一个 TimeSpan 持续时间对象,因此它可以表示为:

public class Time{ 
    [XmlIgnore] 
    public TimeSpan _duration; 
 
    [XmlAttribute(DataType = "duration")] 
    public string value 
        get 
        { 
            return XmlConvert.ToString(this._duration); 
        } 
 
        set 
        { 
            this._duration = XmlConvert.ToTimeSpan(value); 
        } 
    }