Alexandru Pupsa
Alexandru Pupsa

Reputation: 1878

How to deseriealize XML items as different objects?

I am receving an XML from a 3rd party with this format:

<?xml version="1.0" encoding="utf-16"?>
<ColorPages version="1">
                <Page PrintedPagePosition="0" PDFPagePosition="0" IsColor="True" />
                <Ghost PrintedPagePosition="1" PDFPagePosition="1" MayBePrinted="Unprinted" IsColor="False" />
                <Page PrintedPagePosition="2" PDFPagePosition="2" IsColor="False" />
                <Ghost PrintedPagePosition="3" PDFPagePosition="3" MayBePrinted="Unprinted" IsColor="False" />
                <Page PrintedPagePosition="4" PDFPagePosition="4" IsColor="False" />
                <Page PrintedPagePosition="5" PDFPagePosition="5" IsColor="True" />
</ColorPages>

I can easily deserialize this if I ignore the Ghost items, using these classes:

[XmlRoot("ColorPages")]
public class ColorPages
{
    public ColorPages() { Items = new List<Page>(); }
    [XmlElement("Page")]
    public List<Page> Items { get; set; }
}

public class Page
{
    [XmlAttribute("PDFPagePosition")]
    public string PDFPagePosition { get; set; }
    [XmlAttribute("IsColor")]
    public string IsColor { get; set; }
}

Now, I know I have to create a BasePage class that is the base class for both Page and Ghost, but I'm not sure how to make the deserializer handle this.

Upvotes: 1

Views: 27

Answers (1)

bogdanbrudiu
bogdanbrudiu

Reputation: 564

[XmlRoot("ColorPages")]
public class ColorPages
{
    [XmlElement("Ghost")]
    List<Ghost> ghost{ get; set; }

    [XmlElement("Page")]
    List<Page> page{ get; set; }
}
[XmlRoot("Ghost")]
public class Ghost
{

}
[XmlRoot("Page")]
public class Page
{

}

Upvotes: 1

Related Questions