C# XML Linq Pointing to/Reading Node -
i can't seem point , read correct information. i'm new using linq , have tried (after loading document xdocument , xelement) select, root.xelement, descendant, element, node etc. , haven't found proper way of pointing i'm trying target. have xml document looks now.
<contacts> <entryname> <name>name1</name> <email>email</email> <eil>1</eil> <notes>notes</notes> </entryname> </contacts> i need pull list of entrynames , place them in listbox1. when user selects one, gathers takes "listbox1.selecteditem" , gather's email address associated , places in textbox. "entryname" during runtime replaced textfield. recent try this:
var xml = xdocument.load(apppath + @"\contacts.clf"); var entries = xml.element("contacts").value.tostring(); foreach (var entry in entries) { listbox1.items.add(entry.tostring()); } which gets me nothing characters @ time of complete file due foreach function. i'm looking in listbox contacts:
entryname entryname2 entryname2...etc and when selected (from entryname2) pulls email field , places in textbox. please forgive , obvious or dumb mistake, new this. thanks.
i wrote quick example on how achieve this
public partial class form1 : form { xdocument doc; public form1() { initializecomponent(); doc = xdocument.load(apppath + @"\contacts.clf"); var entrynames = doc.root.elements("entryname") .select(elem => elem.element("name").value ).toarray(); listbox1.items.addrange(entrynames); } private void listbox1_selectedvaluechanged(object sender, eventargs e) { textbox1.text = doc.root.elements("entryname") .firstordefault(node => node.element("name").value == listbox1.selecteditem.tostring()) .element("email").value; } } however seems trouble find email. would, instead handle this:
public partial class form1 : form { xdocument doc; public form1() { initializecomponent(); string apppath = "."; doc = xdocument.load(apppath + @"\contacts.clf"); var contacts = doc.root.elements("entryname") .select( elem => new contact { name = elem.element("name").value, email = elem.element("email").value, eil = elem.element("eil").value, notes = elem.element("notes").value } ).tolist(); listbox1.datasource = contacts; listbox1.displaymember = "name"; } private void listbox1_selectedvaluechanged(object sender, eventargs e) { textbox1.text = (listbox1.selecteditem contact).email; } } public class contact { public string name { get; set; } public string email { get; set; } public string eil { get; set; } public string notes { get; set; } }
Comments
Post a Comment