Deserialize XML into C# object with list -


i'm trying deserialize xml c# object has numerous elements of same type. i've pared down contents clarity. c# class looks this:

[xmlinclude(typeof(rootelement))] [xmlinclude(typeof(entry))] [serializable, xmlroot("form")] public class deserializedclass {     public list<entry> listentry;     public rootelement rootelement { get; set; } } 

then define entry , rootelement classes 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 structure of xml i'm trying deserialize looks 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 can see there multiple rootelement elements want deserialize list of c# object. deserialize use following:

xmlserializer serializer = new xmlserializer(typeof(deserializedclass));     using (stringreader reader = new stringreader(xml)) {     deserializedclass deserialized = (deserializedclass)serializer.deserialize(reader);     return deserialized; } 

any ideas how fix it?

i tweaked classes little bit deserialization code 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 works fine.

i don't know why declared xmlroot "form" there no element in xml name replaced "entry".

you cannot use entry class entryvalue1 , entryvalue2 properties because direct children of root (event) , there no child entry. in short classes must reflect hierarchy of xml deserialization can work properly.


Comments