两个用于记住解析的类:
class Answer
{
public int Index { get; set; }
public bool Correct { get; set; }
public string Desc { get; set; }
}
class Question
{
public int Id { get; set; }
public string Content { get; set; }
public string MainQuestion { get; set; }
public int MainQuestionContent { get; set; }
public List<Answer> Answers { get; set; } = new List<Answer>();
}
接下来,XML 本身及其解析:
static void Main(string[] args)
{
string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<testing>
<questions>
<question id=""1"" content=""hi"">
<main_question content=""1"">Вопрос 1</main_question>
<answer index=""1"" correct=""true"">Ответ 1</answer>
<answer index=""2"" correct=""true"">Ответ 2</answer>
<answer index=""3"" correct=""false"">Ответ 3</answer>
</question>
</questions>
</testing>";
XElement elements = XElement.Parse(xml);
List<Question> questionsList = new List<Question>();
Question itemQuestion;
Answer itemAnswer;
foreach (XElement question in elements.Element("questions").Elements("question"))
{
itemQuestion = new Question();
itemQuestion.Id = Convert.ToInt32(question.Attribute("id")?.Value);
itemQuestion.Content = question.Attribute("content")?.Value;
itemQuestion.MainQuestion = question.Element("main_question")?.Value;
itemQuestion.MainQuestionContent = Convert.ToInt32(question.Element("main_question")?.Attribute("content")?.Value);
var answers = from a in question.Elements("answer")
select new
{
AttributeIndex = a.Attribute("index")?.Value,
AttributeCorrect = a.Attribute("correct")?.Value,
Answer = a?.Value
};
if (answers.Any())
{
foreach (var item in answers)
{
itemAnswer = new Answer();
itemAnswer.Index = Convert.ToInt32(item.AttributeIndex);
itemAnswer.Correct = Convert.ToBoolean(item.AttributeCorrect);
itemAnswer.Desc = item.Answer;
itemQuestion.Answers.Add(itemAnswer);
}
}
questionsList.Add(itemQuestion);
}
}
我想把foreach (XElement question in elements.Element("questions").Elements("question"))
它变成 LINQ 查询,但我不知道该怎么做。
感谢@Grundy 的提示,原来是这样优化的:
List<Question> questionsList = (from question in elements.Element("questions").Elements("question")
select new Question()
{
Id = Convert.ToInt32(question.Attribute("id")?.Value),
Content = question.Attribute("content")?.Value,
MainQuestion = question.Element("main_question")?.Value,
MainQuestionContent = Convert.ToInt32(question.Element("main_question")?.Attribute("content")?.Value),
Answers = (from a in question.Elements("answer")
select new Answer
{
Index = Convert.ToInt32(a.Attribute("index")?.Value),
Correct = Convert.ToBoolean(a.Attribute("correct")?.Value),
Desc = a?.Value
}).ToList()
}).ToList();
其实代码等同于通常的
select例如像这样: