Reputation: 2381
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.
Upvotes: 1
Views: 2505
Reputation: 8482
You can use a common class for both elements, if they have the same structure:
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;}
}
UPDATE:
The Time:value
seems like a TimeSpan duration object, so it can be presented as:
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);
}
}
Upvotes: 4