我正在尝试从 XML 文件中读取并使用它来填充我创建的问题对象。这是 XML:
<?xml version="1.0" encoding="utf-8" ?>
<quiz>
<problem>
<question>Which of the following languages could be used in both Visual Studio and Unity?</question>
<answerA>Cobol</answerA>
<answerB>C#</answerB>
<answerC>C−−</answerC>
<answerD>French</answerD>
<correct>B</correct>
</problem>
<problem>
<question>What does XML stand for?</question>
<answerA>eXtremely Muddy Language</answerA>
<answerB>Xerxes, the Magnificent Chameleon</answerB>
<answerC>eXtensible Markup Language</answerC>
<answerD>eXecutes with Multiple Limitations</answerD>
<correct>C</correct>
</problem>
</quiz>
这是我正在使用的课程。问题出在 loadQuestions() 方法中。
public partial class frmQuestions : Form
{
private XmlDocument doc;
private XmlNode theQuiz;
private List<Question> questions;
private Random random;
public frmQuestions(string docName)
{
InitializeComponent();
doc = new XmlDocument();
doc.Load(docName);
questions = new List<Question>();
loadQuestions();
displayQuestion();
}
private void frmQuestions_Load(object sender, EventArgs e)
{
}
private void loadQuestions()
{
string question, a, b, c, d, correct;
theQuiz = doc.FirstChild;
for(int i = 0; i < theQuiz.ChildNodes.Count; i++)
{
XmlNode theQuestion = theQuiz.ChildNodes[i];
question = theQuestion["question"].InnerText;
a = theQuestion["answerA"].InnerText;
b = theQuestion["answerB"].InnerText;
c = theQuestion["answerC"].InnerText;
d = theQuestion["answerD"].InnerText;
correct = theQuestion["correct"].InnerText;
questions.Add(new Question(question, a, b, c, d, correct));
}
}
private void displayQuestion()
{
Random random = new Random();
int randomNumber = random.Next(1, questions.Count);
lblQuestion.Text = questions[randomNumber].getQuestion();
lblA.Text = questions[randomNumber].getA();
lblB.Text = questions[randomNumber].getB();
lblC.Text = questions[randomNumber].getC();
lblD.Text = questions[randomNumber].getD();
}
}
我发现的问题是 theQuiz.ChildNodes.Count = 0。
有人知道我要去哪里错了吗?