この xml をクラスに読み込む必要があります。LINQ to XML は初めてです。
<quiz>
<step id="1">
<question id="1">
<text>What is the world’s tallest tower?</text>
<answers>
<answer id="1" value="0">Eiffel Tower</answer>
<answer id="2" value="0">Petronas Tower</answer>
<answer id="3" value="0">Canton Tower</answer>
<answer id="4" value="1">Tokyo Skytree </answer>
</answers>
</question>
</step>
</quiz>
この 2 つのクラスを作成しましたが、情報を簡単に読み取る方法がわかりません。私の頭はそれから壊れています。
public class QuizQuestion
{
public int StepId { get; set; }
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public List<QuizAnswer> Answers { get; set; }
}
public class QuizAnswer
{
public int AnswerId { get; set; }
public int CorrectAnswer { get; set; }
public String AnswerText { get; set; }
}
私はこれを試しましたが、それが正しいかどうかはわかりません
var quizQuestions = new List<QuizQuestion>();
_cacheLock.EnterWriteLock();
try
{
XDocument xmlDoc = XDocument.Load(_questionsFilePath);
XDocument data = XDocument.Load(_questionsFilePath);
quizQuestions = (from c in data.Descendants("quiz")
orderby c.Attribute("question")
select new QuizQuestion()
{
StepId = Convert.ToInt32(c.Attribute("Id").Value),
QuestionId = Convert.ToInt32(c.Attribute("Id").Value),
QuestionText = c.Value
}).ToList();
foreach (QuizQuestion quiz in quizQuestions)
{
quiz.Answers =
(from c in data.Descendants("quiz")
orderby c.Attribute("question")
where Convert.ToInt32(c.Attribute("Id").Value) == 1
select new QuizAnswer()
{
AnswerId = Convert.ToInt32(
c.Attribute("id").Value),
AnswerText = c.Value,
CorrectAnswer = Convert.ToInt32(
c.Attribute("value").Value)
}).ToList();
}
}
catch (NullReferenceException e)
{
}