XML to List in C# -
this xml:
<packages> <package> <id>1</id> <prerequisites> <prerequisite>7</prerequisite> <prerequisite>8</prerequisite> </prerequisites> </package> <package> <id>2</id> ..... </package> .... </packages>
and list:
class lista { public int id {get; set;} public list<int> pre{get;set;} }
how can add xml pattern list of lista class , have got far bot put 1 in second list.
xdocument xdoc = xdocument.load("employee.xml"); var listpckage = (from item in xdoc.descendants("package") orderby item.element("id").value select new { id = item.element("id").value, prerequisite = item.element("prerequisites").element("prerequisite").value, }).tolist();
foreach works shoing them
foreach (var item in listpckage) { console.writeline(item.id); foreach (var item1 in listpckage) { console.writeline(item1.prerequisites); } }
as john sket mentioned in comment question, 1 way achieve use linq xml.
//string xcontent = @"xml content here"; //xdocument xdoc = xdocument.parse(xcontent); xdocument xdoc = xdocument.load("fullpathtoxml"); list<lista> resultlist = xdoc.descendants("package") .select(x=> new lista { id = convert.toint32(x.element("id").value), pre = x.descendants("prerequisite").select(y=>convert.toint32(y.value)).tolist() }) .tolist();
but, i'd suggest use xmlserialization/xmldeserialization.
Comments
Post a Comment