c# - randomly Select XML nodes with same names -
i have xml file:
<main> <qa> <question>what favorite color?</question> <!--pick random!--> <answer>blue</answer> <answer>red</answer> <answer>green</answer> <answer>yellow</answer> </qa> <qa> <question>what favorite programming language?</question> <!--pick random!--> <answer>php</answer> <answer>c#</answer> <answer>java</answer> <answer>vb.net</answer> </qa>
i want when user enter 1 of question specified in above xml file, program pick random answer nodes. example when user enters "what favorite programming language?" in textbox, program must generate php,c#,java or vb.net randomly.
this code not correct:
xmldocument xml = new xmldocument(); xml.load("qa.xml"); xmlnodelist xlist = xml.selectnodes("main/qa"); foreach (xmlnode xn in xlist) { string question = xn["question"].innertext; if (question == txtquestion.text) { xmlnodelist answerlist = xml.selectnodes("main/qa/answer"); foreach (xmlnode ans in answerlist) { console.writeline(ans.innertext); } } }
output:
blue red green yellow php c# java vb.net
please help.
try this:
xmldocument xml = new xmldocument(); xml.load("qa.xml"); xmlnodelist xlist = xml.selectnodes("main/qa"); foreach (xmlnode xn in xlist) { string question = xn["question"].innertext; if (question == txtquestion.text) { xmlnodelist answerlist = xn.selectnodes("./answer"); foreach (xmlnode ans in answerlist .cast<xmlnode>() .orderby(elem => guid.newguid())) { console.writeline(ans.innertext); } } }