c# - How to navigate though xml nodes? -
i have 2 buttons , 3 labels in windows form , xml file.
this xml:
<qustions> <question id="1" cat="5"> "question text 1" </question> <question id="2" cat="2"> "question text 2" </question> <question id="3" cat="3"> "question text 3" </question> <question id="4" cat="5"> "question text 4" </question> <question id="5" cat="8"> "question text 5" </question> </qustions>
i want show every question body , category in form , navigate through them buttons.
which way best approach achieve this?
try following code uses xml linq
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.xml; using system.xml.linq; using system.io; namespace windowsformsapplication1 { public partial class form1 : form { public int questionindex = 0; public list<xelement> questions = null; public form1() { initializecomponent(); string xml = "<qustions>" + "<question id=\"1\" cat=\"5\">" + "\"question text 1\"" + "</question>" + "<question id=\"2\" cat=\"2\">" + "\"question text 2\"" + "</question>" + "<question id=\"3\" cat=\"3\">" + "\"question text 3\"" + "</question>" + "<question id=\"4\" cat=\"5\">" + "\"question text 4\"" + "</question>" + "<question id=\"5\" cat=\"8\">" + "\"question text 5\"" + "</question>" + "</qustions>"; xdocument doc = xdocument.parse(xml); questions = doc.descendants("question").tolist(); displayquestion(questionindex); } private void buttonprevious_click(object sender, eventargs e) { if (questionindex != 0) { displayquestion(--questionindex); } } private void buttonnext_click(object sender, eventargs e) { if (questionindex < questions.count - 1) { displayquestion(++questionindex); } } public void displayquestion(int index) { textboxid.text = questions[index].attribute("id").value; textboxcat.text = questions[index].attribute("cat").value; textboxcattext.text = questions[index].value; } } }
Comments
Post a Comment