vendredi 31 juillet 2015

deserialize xml into inherited classes from base class

I have the following xml structure:

<Root1>
    <name>Name1</name>
    <company>Comp1</company>
    <url>site.com</url>
    <elements>
        <element id="12" type="1">
            <url>site1.com</url>
            <price>15000</price>
            ...
            <manufacturer_warranty>true</manufacturer_warranty>
            <country_of_origin>Япония</country_of_origin>
        </element>
        <element id="13" type="2">
            <url>site2.com</url>
            <price>100</price>
            ...
            <language>lg</language>
            <binding>123</binding>
        </element>
    </elements>
</Root1>

I need deserialize this xml structure to object. How you can see the element contains some equals field: url and price. I would like to move these fields into a separate class and then inherit this class by other classes.

I created the class Root1:

namespace app1
{
    [Serializable]
    public class Root1
    {
        [XmlElement("name")] 
        public string Name { get; set; }

        [XmlElement("company")] 
        public string Company { get; set; }

        [XmlElement("url")] 
        public string Url { get; set; }

        [XmlElement("elements")]
        public List<Element> ElementList { get; set; }
    }
}

and then I created base class for Element:

[Serializable]
    public class Element
    {
        [XmlElement("url")] 
        public string Url { get; set; }

        [XmlElement("price")] 
        public string Price { get; set; }
    }

and then I inherited this class by other classes:

[Serializable]
public class Element1 : Element
{
    [XmlElement("manufacturer_warranty")] 
    public string mw { get; set; }

    [XmlElement("country_of_origin")] 
    public string co { get; set; }
}

[Serializable]
public class Element2 : Element
{
    [XmlElement("language")] 
    public string lg { get; set; }

    [XmlElement("binding")] 
    public string bind { get; set; }
}

When I deserializing this xml to object Root1 I get the object - it is ok. But the List of Elements contains only Element objects not Element1 and Element2 objects.

How I do deserialize this xml that list of Elements contains Element1 and Element2 objects?

Aucun commentaire:

Enregistrer un commentaire