[英]How to deserialize xml nodes with a different name into a list
我想使用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
的屬性。
我怎樣才能做到這一點。
如果元素具有相同的結構,則可以對這兩個元素使用公共類:
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;}
}
更新: Time:value
看起來像TimeSpan持續時間對象,因此它可以表示為:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.