簡體   English   中英

C#將XML元素讀取到2個單獨的列表中

[英]C# Reading XML elements into 2 separate lists

我正在使用C#作為控制台應用程序創建測驗。

我有一個XML文件,其中包含a)問題b)答案和c)錯誤的答案。

我可以從XML文件中讀取問題。

但是,我無法弄清楚我需要為每個隨機生成的閱讀問題關聯錯誤和正確答案的邏輯。

這是我的XML文件的副本。

<?xml version="1.0" encoding="utf-8"?>
<Question xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <theQuestion>How many players in a football team?</theQuestion>
  <answerA>12</answerA>
  <answerB>10</answerB>
  <answerC>20</answerC>
  <answerD>11</answerD>
  <correctAnswer>11</correctAnswer>
  <theQuestion>How many minutes in a football game?</theQuestion>
  <answerA>90</answerA>
  <answerB>45</answerB>
  <answerC>60</answerC>
  <answerD>77</answerD>
  <correctAnswer>90</correctAnswer> 
</Question>

這是我的代碼的一部分:

  ProcessData data = new ProcessData();

  //load questions from XML file and store in list
  var questions =  data.LoadQuizQuestions();

  //create a question object
  Question q = new Question();

  //get a question randomly generated from questions list 
  int index = new Random().Next(questions.Count);

  //display the randomly generated question
  Console.WriteLine(questions[index]);

  Console.ReadLine();

這是我的LoadQuizQuestions()

    public List<string> LoadQuizQuestions()
    {
      //create empty list to store quiz questions read in from file
      List<string> questions = new List<string>();

      //load questions from file into list
      questions =
        XDocument.Load(@"C:\Development\Learning\Files\qsFile.xml").Descendants("theQuestion").Select(o => o.Value).ToList();

      //return list of questions
      return questions;
   }

我希望在顯示每個隨機問題時,也顯示該問題的相關答案,並將“正確答案”讀入一個變量,我可以根據該變量檢查用戶輸入。

請幫助我了解我知道我將要釘牢這個:-)

謝謝

  1. 將xml讀入List<Question>集合
  2. 選擇一個隨機物品
    1. 顯示問題和選項
    2. 要求用戶輸入
    3. 比較用戶輸入和正確答案
  3. 利潤

編輯 :您的XML輸入將您的數據視為順序的 ,而不是分層的; 當您嘗試閱讀問題時,這將導致潛在的問題。

您應該考慮這樣的結構:

<Questions>
    <Question>
        <Title>How many players in a football team?</Title>
        <Options>
            <Option>12</Option>
            <Option>10</Option>
            <Option>20</Option>
            <Option IsCorrect='true'>11</Option>
        </Options>
    </Question>
    <Question>
        <Title>How many minutes in a football game?</Title>
        <Options>
            <Option IsCorrect='true'>90</Option>
            <Option>45</Option>
            <Option>60</Option>
            <Option>77</Option>
        </Options>
    </Question>
</Questions>

這將使手動讀取XML或將其直接反序列化為List<Question>集合變得更加容易。

我做保留的選項,如果這是一個正確的答案,因為這可能是足夠的靈活性,多個正確答案的決定。

class Question
{
    public string Title         { get; private set; }
    public List<Option> Options { get; private set; }

    public Question()
    {
    }

    public Question(XmlElement question) : this()
    {
        this.Title   = question["Title"].InnerText;
        this.Options = question.SelectNodes("Options/Option")
            .OfType<XmlElement>()
            .Select(option => new Option(option))
            .ToList();
    }
}

在這里沒什么大不了的:我們只讀取一個XmlElement並將項目反序列化委托給Option類。

class Option
{
    public string Title         { get; private set; }
    public bool   IsCorrect     { get; private set; }

    public Option()
    {
    }

    public Option(XmlElement option) : this()
    {
        this.Title = option.InnerText;
        this.IsCorrect = option.GetAttribute("IsCorrect") == "true";
    }
}

同樣的交易。

通過這種結構,您可以執行以下操作:

var xml = new XmlDocument();
    xml.LoadXml(@"...");

var random = new Random();
var questions = xml.SelectNodes("//Question")
    .OfType<XmlElement>()
    .Select (question => new Question(question))
    .OrderBy(question => random.Next())
    .ToList();

foreach (var question in questions)
{
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine(question.Title);
    foreach (var option in question.Options)
    {
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("\t{0}", option.Title);
    }
    Console.Write("Choose the right option: ");
    var answer = Console.ReadLine();

    if (question.Options.Any(option =>
        option.IsCorrect && answer.Equals(option.Title, 
            StringComparison.InvariantCultureIgnoreCase)))
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("YOU HAVE CHOSEN... WISELY.");
    }
    else
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("You have chosen poorly!");
    }
}

如果您使用包含答案列表的問題對象,如下所示:

public class Question
{
    public int ID { get; set; }
    public string QuestionText { get; set; }

    public List<Answer> Answers { get; set; } 

    public string AnswerText { get; set; }
}

public class Answer
{
    public string ID { get; set; }
    public string AnswerText { get; set; }
}

然后,您可以將問題和答案讀入離散的對象中,例如下面的代碼(免責聲明:未對此進行測試,因此可能需要對其進行調整才能起作用)

   public List<Question> GetQuestions(string xmlFile)
    {
        var questions = new List<Question>();

        var xDoc = XDocument.Load(xmlFile);

        var questionNodes = xDoc.Descendants("theQuestion");

        foreach (var questionNode in questionNodes)
        {

            var question = new Question();
            question.QuestionText = questionNode.Value;

            // do something like this for all the answers
            var answer = new Answer();
            answer.ID = "A";
            var answerA = questionNode.Descendants("answerA").FirstOrDefault();
            if (answerA != null)
                answer.AnswerText = answerA.Value;

            question.Answers = new List<Answer>();
            question.Answers.Add(answer);

            question.AnswerText =
                questionNode.Descendants("correctAnswer").FirstOrDefault().Value;
        }

        return questions;
    } 
}

現在,您已經在單個對象中包含了問題和答案,可以顯示問題,答案,然后根據用戶輸入進行字符串比較以檢查用戶的答案。

您可以檢查我的邏輯以根據需要從XMLNode獲取值。

如何使用C#獲取XML文件中的節點值

如果您可以更改xml結構,請執行以下操作:

<?xml version="1.0" encoding="utf-8"?>
<Questions>
  <Question text="How many players in a football team?">
    <answerA>12</answerA>
    <answerB>10</answerB>
    <answerC>20</answerC>
    <answerD>11</answerD>
    <correctAnswer>11</correctAnswer>
  </Question>
  <Question text="How many minutes in a football game?">
    <answerA>90</answerA>
    <answerB>45</answerB>
    <answerC>60</answerC>
    <answerD>77</answerD>
    <correctAnswer>90</correctAnswer>
  </Question>
</Questions>

然后使用以下類反序列化:

public class Questions
{
    [XmlElement("Question")]
    public List<Question> QuestionList { get; set; } = new List<Question>();
}

public class Question
{
    [XmlAttribute("text")]
    public string Text { get; set; }

    public string answerA { get; set; }
    public string answerB { get; set; }
    public string answerC { get; set; }
    public string answerD { get; set; }
    public string correctAnswer { get; set; }
}

這段代碼:

string path = "yourxmlfile.xml";

XmlSerializer serializer = new XmlSerializer(typeof(Questions));

StreamReader reader = new StreamReader(path);
var qs = (Questions)serializer.Deserialize(reader);
reader.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM