For example I have an xml:
<MyFruit>
<Fruit>
<Name>Apple</Name>
<Size>Big</Size>
</Fruit>
<Fruit>
<Name>Orange</Name>
<Price>10.00</Price>
</Fruit>
</MyFruit>
You may notice that the fruit
nodes contain different elements, that's my hurt:(
Then I defined following classes in order to hold the deserialized object:
public class MyFruit
{
public List<Fruit> Fruits { get; set; }
}
public abstract class Fruit
{
public string Name { get; set; }
}
public class Apple : Fruit
{
public string Size { get; set; }
}
public class Orange : Fruit
{
public float Price { get; set; }
}
It didn't work.
I also tried:
- Adding
[XmlInclude(typeof (Apple))]
and[XmlInclude(typeof (Orange))]
attributes to thefruit
base class to specify the concrete derived classes - Adding
[XmlElement(typeof (Apple))]
and[XmlElement(typeof (Orange))
attributes to theFruits
property of theMyFruit
class
Neither of them works.
So I wonder is there a way that can control the deserialization process base on element's value(if the name is Apple
, deserialize to Apple
class, Orange
to Orange
class...), or maybe there are some better ways?
UPDATE
I wrote an extension method to deserialize xml:
public static T Deserialize<T>(this string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringReader = new StringReader(xml);
using (var reader = XmlReader.Create(stringReader))
{
return (T) xmlserializer.Deserialize(reader);
}
}
catch (Exception ex)
{
throw new Exception("反序列化发生错误", ex);
}
}