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:
- you specified "car" element's name "car".
- the
car
property should not decorated[xmlarray("cars")]
, "cars" xml element defined oncars
class itself. - the
car
property should defined usingxmlelement
, notxmlarrayitem
.
Comments
Post a Comment