c# - read an xml file with complex struct asp.net mvc -
i'm beginner on asp.net , want read red data xml file complex structure. works when structures simple.
this xml file
<flights> <flight> <content>gds</content> <currency>mad</currency> <amount>11777</amount> <duration>02h30m</duration> <stops>0</stops> <officeid>oooo01</officeid> <itineraries> <itinerary> <ref>1</ref> <duration>02h30m</duration> <stops>0</stops> <availableseats>7</availableseats> </itinerary> </itineraries> </flight> </flights>
i extract models
[serializable] [xmlroot("flights"), xmltype("flights")] public class flights { public string content { get; set; } public string currency { get; set; } public int amount { get; set; } public string duration { get; set; } public int stops { get; set; } public string officeid{ get; set; } public list< itineraries> itinerary { get; set; } } [serializable] [xmlroot("itineraries"), xmltype("itineraries")] public class itineraries { public string ref { get; set; } public string duration { get; set; } public string stops { get; set; } public string availableseats { get; set; } }
i have xml reader read simple attributes
public list<flights> retrunlistofproducts() { string xmldata = httpcontext.current.server.mappath("~/app_data/flightdata.xml");//path of xml script dataset ds = new dataset();//using dataset read xml file ds.readxml(xmldata); var flights = new list<flights>(); flights = (from rows in ds.tables[0].asenumerable() select new flights { //convert row int content = rows[0].tostring(), currency = rows[1].tostring(), amount = convert.toint32(rows[2].tostring()), duration = rows[3].tostring(), stops = convert.toint32(rows[4].tostring()), officeid = rows[5].tostring(), itinerary <--- how read part? }).tolist(); return flights; }
what can solve problem?
will consider using xmlserializer deserialize data? works load xml file object.
streamreader sr = new streamreader(xmldata); xmlserializer xs = new xmlserializer(typeof(flight)); flights f = xs.deserialize(sr) flight;
however, may need modification in flight type
- you should use array instead of list<>
- add attribute [xmlarray("name")] , [xmlarrayitem("name")] in array type members.
for example
[xmlarray("itineraries")] [xmlarrayitem("itinerary")] public itinerary[] itinerary;
Comments
Post a Comment