如何将用户的多个答案与我的XML文件进行比较?

时间:2012-05-20 06:34:01

标签: c# asp.net xml

我正在创建一个采访网页,用户可以在文本框内的屏幕上回答提到的特定问题。我有一个检查按钮。点击此按钮,我需要比较在特定问题文本框中输入的答案,并通常通过与我的XML文件对特定问题的答案进行比较来显示答案的准确性百分比。

这是我的XML文件“

<?xml version="1.0" encoding="utf-8" ?> 
<Questions> 
  <Question id="1">What is IL code </Question> 
  <Answer id="1">Half compiled, Partially compiled code </Answer> 
  <Question id="2">What is JIT </Question> 
  <Answer id="2">IL code to machine language </Answer> 
 <Question id="3">What is CLR </Question> 
  <Answer id="3">Heart of the engine , GC , compilation , CAS(Code access security) , CV ( Code verification) </Answer> 
</Questions>

这是我的表格:

enter image description here

下面是我的检查按钮的代码,我只与一个标签和文本框进行了比较。它有效。

XmlDocument docQuestionList = new XmlDocument();// Set up the XmlDocument //
docQuestionList.Load(@"C:\Users\Administrator\Desktop\questioon\questioon\QuestionAnswer.xml"); //Load the data from the file into the XmlDocument //
XmlNodeList AnswerList = docQuestionList.SelectNodes("Questions/Question");
foreach (XmlNode Answer in AnswerList)
{
    if (Answer.InnerText.Trim() == Label2.Text)
    {
        string[] arrUserAnswer = TextBox1.Text.Trim().ToLower().Split(' ');
        string[] arrXMLAnswer = Answer.NextSibling.InnerText.Trim().ToLower().Split(' ');
        List<string> lststr1 = new List<string>();
        foreach (string nextStr in arrXMLAnswer)
        {
            if (Array.IndexOf(arrUserAnswer, nextStr) != -1)
            {
                lststr1.Add(nextStr);
            }
        }
        if (lststr1.Count > 0)
        {
            TextBox1.Text = ((100 * lststr1.Count) / arrXMLAnswer.Length).ToString() + "%";
        }
        else
        {
            TextBox1.Text = "0 %";
        }
    }
}

正如您所看到的,我只比较了一个问题的值和相应的答案,但我希望这不是硬编码的。相反,它应该采取问题和相应的文本框回答并与我的XML文件进行比较。我怎样才能实现目标?

1 个答案:

答案 0 :(得分:2)

我只是保持简单,并设置一系列问题,答案和用户的答案......

XDocument xdoc = XDocument.Load(@"C:\Users\Administrator\Desktop\questioon\questioon\QuestionAnswer.xml");
string[] questions = xdoc.Root.Elements("Question").Select(x => (string)x).ToArray();
string[] answers = xdoc.Root.Elements("Answer").Select(x => (string)x).ToArray();
string[] userAnswers = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
for (int i=0 ; i < questions.Length ; i++)
{
    // handle responses
    string[] words = answers[i].Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Select(w => w.ToLower().Trim()).ToArray();
    string[] userWords = userAnswers[i].Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Select(w => w.ToLower().Trim()).ToArray();
    string[] correctWords = words.Intersect(userWords);

    // do percentage calc using correctWords.Length / words.Length
}