C# Deserialize of XML into entity -


i'm trying deseaqralize xml document list of car objects, coming null.

here's sample xml document based on post: how deserialize xml document

<?xml version="1.0" encoding="utf-8"?> <cars>   <car id="1">     <stocknumber>1020</stocknumber>     <make>nissan</make>     <model>sentra</model>   </car>   <car id="2">     <stocknumber>1010</stocknumber>     <make>toyota</make>     <model>corolla</model>   </car>   <car id="3">     <stocknumber>1111</stocknumber>     <make>honda</make>     <model>accord</model>   </car> </cars> 

required classes:

[serializable()] public class car {     [system.xml.serialization.xmlattribute("id")]     public int id { get; set; }      [system.xml.serialization.xmlelement("stocknumber")]     public string stocknumber { get; set; }      [system.xml.serialization.xmlelement("make")]     public string make { get; set; }      [system.xml.serialization.xmlelement("model")]     public string model { get; set; } }  [serializable()] [system.xml.serialization.xmlroot("cars")] public class cars {     [xmlarray("cars")]     [xmlarrayitem("car", typeof(car))]     public list<car> car { get; set; }         } 

deserialize function:

public void parsereturnxmlforvirtualevent2() {     cars cars = null;     string path = @"e:\projects\newcars.xml";      xmldocument pdoc = new xmldocument();     pdoc.load(path);     xdocument doc = new xdocument();     doc = xdocument.parse(pdoc.outerxml);                  system.xml.serialization.xmlserializer serializer = new system.xml.serialization.xmlserializer(typeof(cars));      system.xml.xmlreader reader = doc.createreader();     cars = (cars)serializer.deserialize(reader);     reader.close();      //return cars; } 

let me know if need me provide further details.

you can fix replacing car property with:

[xmlelement("car", typeof(car))] public list<car> car { get; set; } 

your code had 3 problems:

  1. you specified "car" element's name "car".
  2. the car property should not decorated [xmlarray("cars")], "cars" xml element defined on cars class itself.
  3. the car property should defined using xmlelement , not xmlarrayitem.

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -