CorribView
CorribView

Reputation: 741

Deserialize XML into C# object with list

I'm trying to deserialize an XML into a C# object that has numerous elements of the same type. I've pared down the contents for clarity. My C# class looks like this:

[XmlInclude(typeof(RootElement))]
[XmlInclude(typeof(Entry))]
[Serializable, XmlRoot("Form")]
public class DeserializedClass
{
    public List<Entry> listEntry;
    public RootElement rootElement { get; set; }
}

Then I define the Entry and RootElement classes as follows:

public class RootElement 
{
    public string rootElementValue1 { get; set; }
    public string rootElementValue2 { get; set; }
}

public class Entry
{
    public string entryValue1 { get; set; }
    public string entryValue2 { get; set; }
}

And the structure of the XML I'm trying to deserialize looks like this:

<Entry property="value">
  <entryValue1>Data 1</entryValue1>
  <entryValue2>Data 2</entryValue2>
  <RootElement>
    <rootElementValue1>Data 3</rootElementValue1>
    <rootElementValue2>Data 4</rootElementValue2>
  </RootElement>
  <RootElement>
    <rootElementValue1>Data 5</rootElementValue1>
    <rootElementValue2>Data 6</rootElementValue2>
  </RootElement>
</Entry>

As you can see there will be multiple RootElement elements that I want to deserialize into the List of the C# object. To deserialize I use the following:

XmlSerializer serializer = new XmlSerializer(typeof(DeserializedClass));    
using (StringReader reader = new StringReader(xml))
{
    DeserializedClass deserialized = (DeserializedClass)serializer.Deserialize(reader);
    return deserialized;
}

Any ideas how to fix it?

Upvotes: 1

Views: 5473

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6977

I tweaked your classes a little bit for your deserialization code to work:

[Serializable, XmlRoot("Entry")]
public class DeserializedClass
{
    public string entryValue1;
    public string entryValue2;

    [XmlElement("RootElement")]
    public List<RootElement> rootElement { get; set; }
}

public class RootElement
{
    public string rootElementValue1 { get; set; }
    public string rootElementValue2 { get; set; }
}

Now it works fine.

I don't know why you declared your XmlRoot as "Form" as there is no element in the XML with that name so I replaced it with "Entry".

You cannot use an Entry class with entryvalue1 and entryvalue2 properties because they are direct children of the root (Event) and there is no child as Entry. In short your classes must reflect the hierarchy of the XML so that deserialization can work properly.

Upvotes: 5

Related Questions