c# - Deserialize list set index to object property -
i have following xml
<itemsroot> <itemlist> <item> <name>a</name> <itemlist> <item> <name>aa</name> </item> <item> <name>ab</name> </item> </itemlist> </item> <item> <name>b</name> </item> <item> <name>c</name> </item> </itemlist> </itemsroot>
my classes are
public class item { [xmlignore()] public int itemindex {get;set;} public string name {get;set;} private item[] itemslist; [xmlelement(isnullable = true)] [xmlarrayitem("item", typeof(item))] [xmlarray("itemlist")] public item[] itemslist { { return itemslist; } set { itemslist= value; } } } [xmlroot("itemsroot")] public class itemsroot { private item[] itemslist; [xmlarrayitem("item", typeof(item))] [xmlarray("itemlist")] public item[] itemslist { { return itemslist; } set { itemslist= value; } } }
code deserializing:
public static object xmldeserialize(string dataxml, type objecttype) { xmldocument xdoc = new xmldocument(); xdoc.loadxml(dataxml); xmlnodereader xnodereader = new xmlnodereader(xdoc.documentelement); xmlserializer xmlserializer = new xmlserializer(objecttype); var objectdata = xmlserializer.deserialize(xnodereader); return objectdata; }
so im trying when deserialize xml wanted populate itemindex variable index of object in list.
i.e.
item object name index 0
item object name b index 1 etc
and
item aa index 0 again
item ab index 1
etc
i not concerned when itemindex populated. can happen after deserialization, figured spot doing this.
here pseudo code of how would've done this.
here read xml file disk.
public static ienumerable<xelement> streamxmldoc(stream inputstream, string nodename) { using (var reader = new streamreader(inputstream)) { using (var xmlreader = xmlreader.create(reader)) { xmlreader.movetocontent(); while (xmlreader.read()) { switch (xmlreader.nodetype) { case xmlnodetype.element: if (xmlreader.name == nodename) { var xelement = xelement.readfrom(xmlreader) xelement; if (xelement != null) { yield return xelement; } } break; } } } } }
and then, when call streamxmldoc method, can populate model necessary, example below shows.
var counter = 0; var serializedobjects = xmlhelper.streamxmldoc(fs, nodename); foreach (var element in serializedobjects) { // convert (deserialize) patient xelement instance of despatientmodel class. var item = xmlhelper.xmldeserialize(element.tostring(), typeof(yourtype)); item.itemindex = counter++; }
Comments
Post a Comment