我有一个包含以下内容的xml文件:
<offer>
...
<date type="Foo">Some value 1</date>
<date type="Bar">Some value 2</date>
<date type="Baz">Some value 3</date>
...
</offer>
我有一个这样的枚举:
public enum DateType
{
Foo, Bar, Baz
}
课程:
public class Date
{
public DateType Type { get; set; }
public string Value { get; set; }
}
public class Schedule
{
...
public Date[] Dates { get; set; }
...
}
我需要做什么才能在这个类中反序列化xml?
P.S。因此,我需要在public Date[] Dates { get; set; }
中映射枚举值。
答案 0 :(得分:0)
使用此类:
public enum DateType
{
Foo, Bar, Baz
}
[XmlRoot(ElementName = "date")]
public class Date
{
[XmlAttribute(AttributeName = "type")]
public DateType Type { get; set; }
[XmlText]
public string Value { get; set; }
}
[XmlRoot(ElementName = "offer")]
public class Offer
{
[XmlElement(ElementName = "date")]
public Date[] Dates { get; set; }
}
反序列化:
string lsXml = @"<offer>
<date type=""Foo"">Some value 1</date>
<date type=""Bar"">Some value 2</date>
<date type=""Baz"">Some value 3</date>
</offer>";
XmlSerializer loXmlSerializer = new XmlSerializer(typeof(Offer));
var loOffer = loXmlSerializer.Deserialize(new StringReader(lsXml)) as Offer;
foreach (var loDate in loOffer.Dates)
{
Console.WriteLine($"{loDate.Type}: {loDate.Value}");
}