ambhai
ambhai

Reputation: 31

Polymorphic XML Serialization/DeSerialization to C# objects for varying list of nodes

I have an XML file like this

<xml>
    <nodes>
        <text/>
        <img/>
        <text/>
    </nodes>
</xml>

I want to map C# objects to this, I know how to use XmlArrayItem but only incase where there is only one item type in array. I was thinking how to do it using a base class for img and text nodes. But can anyone show my code for C# attributes that I can use to auto DeSerialize this xml into C# objects. Using LINQ is not needed.

Here is how I plan to do but its not working:

[Serializable]
[XmlRoot ( "textfile" )]
public class TextFile
{

    [XmlArray ( "nodes" )]
    [XmlArrayItem ( "text", typeof(NodeText)), XmlArrayItem ( "img", typeof(NodeImg) )]
    public List<NodeBase Nodes
    {
        get;
        set;
    }


}

[Serializable]
public class NodeBase
{
}

[Serializable]
public class NodeText : NodeBase
{


[XmlText]
public String CDataContent
{
        get;
        set;
    }
}

[Serializable]
public class NodeImg : NodeBase
{

    [XmlAttribute ( "width" )]
    public Int32 Width
    {
        get;
        set;
    }

    [XmlAttribute ( "height" )]
    public Int32 Height
    {
        get;
        set;
    }

    [XmlAttribute ( "src" )]
    public String SourceImgStr
    {
        get;
        set;
    }
}

Upvotes: 0

Views: 2255

Answers (1)

mtijn
mtijn

Reputation: 3678

afaik you don't need the XmlArrayItem attribute with type declarations, just add this to your base class:

[Serializable]
[XmlInclude(typeof(NodeText))]
[XmlInclude(typeof(NodeImg))]
public class NodeBase
{}

Upvotes: 1

Related Questions