我需要将此 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>
我已经创建了这两个类,但我不确定如何轻松读取信息。我的头被它毁了。
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)
{
}