c# - How can I create a collection of business objects from multiple elements in a XmlDocument -
i'm trying create collection of business objects following xml document using .net 4.0/c#
<webservices errorfound="false" serverdatetime="30/11/2010 14:58:58"> <results> <users totalresults="5"> <username userid="2">john</username> <username userid="3">dave</username> <username userid="4">jim</username> <username userid="5">bob</username> </users> </results> </webservices>
this class need create
public class user { public string name { get; set; } public int id { get; set; } }
each of users child elements should new instance of class. far have method accepts xmldocument.
public static ienumerable<user> getuser(xmldocument xmldoc) { xmlreader reader = xmlreader.create(new stringreader(xmldoc.outerxml)); xdocument doc = xdocument.load(reader); var user = u in doc.descendants("webservices").descendantsandself("users") select new user() { name = u.element("username").value, id = int.parse(u.element("username").attribute("userid").value) }; list<user> userinstance = user.tolist(); ienumerable<user> users= u in userinstance select u; return users; }
this works fine far producing 1 instance of object first child element concerned unsure how create multiple instances elements. need able return collection of user objects eg collection<user> users = new collection<user>()
i barking wrong tree. appreciated.
using xpath can write code this:
public class user { public string name { get; set; } public int id { get; set; } } static void main(string[] args) { string xml = "<webservices errorfound='false' serverdatetime='30/11/2010 14:58:58'>" + "<results>" + "<users totalresults='5'>" + "<username userid='2'>john</username>" + "<username userid='3'>dave</username>" + "<username userid='4'>jim</username>" + "<username userid='5'>bob</username>" + "</users>" + "</results>" + "</webservices>"; xmldocument doc = new xmldocument(); doc.loadxml(xml); var users = usernameelement in doc.selectnodes("/webservices/results/users/username").oftype<xmlelement>() select new user { name = usernameelement.innertext, id = int32.parse(usernameelement.getattribute("userid")) }; foreach (var user in users) { console.writeline(user.id.tostring() + ": " + user.name); } }
Comments
Post a Comment