Friday, September 21, 2012

ASP.NET/C#/XML - Get one random node from XML file

I will show the way I retrieve a single random node from XML file using ASP.NET/C#. In this case I will use an XML file used to store math problems and solution for human verification on an online "Contact Us" form.

XML file format:
<human_check>
  <qa>
    <q>2 + 2</q>
    <a>4</a>
  </qa>
  <qa>
    <q>1 + 2</q>
    <a>3</a>
  </qa>
  <qa>
    <q>6 + 3</q>
    <a>9</a>
  </qa>
  <qa>
    <q>3 + 5</q>
    <a>7</a>
  </qa>
</human_check>

C# code:
public static string get_math_problem(){

Random rnd = new Random();
XDocument questions = XDocument.Load(@"C:\FILE_LOCATION\human_check.xml");

var qas = questions.Descendants("qa");
int qaCount = qas.Count();
return qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;
}



Cheers!

No comments:

Post a Comment