简体   繁体   中英

How to deserialize xml nodes with a different name into a list

I want to deserialize an xml file using c#.

the file has this form:

<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>

I want to deserialize all child elements of parent into a List<Myclass> with TotProd/ProdToNet as a property of Myclass .

How can i do this.

You can use a common class for both elements, if they have the same structure:

public class Time{
    [XmlAttrubute]
    public string value {get; set; }
    [XmlText]
    public string Text {get;set;} // this will hold the innerText value ("10") of <Time>
}

public class Prod{

    [XmlAttrubute]
    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;}
}

UPDATE: The Time:value seems like a TimeSpan duration object, so it can be presented as:

public class Time{
    [XmlIgnore]
    public TimeSpan _duration;

    [XmlAttrubute(DataType = "duration")]
    public string value
        get
        {
            return XmlConvert.ToString(this._duration);
        }

        set
        {
            this._duration = XmlConvert.ToTimeSpan(value);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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