我有以下XML並希望返回所有的「答案」兒童名單返回具有相同名稱的多個XML兒童LINQ
<quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="quiz.xsd">
<mchoice>
<question>What is the capital city of Australia?</question>
<answer>Sydney</answer>
<answer correct="yes">Canberra</answer>
<answer>Melbourne</answer>
<answer>Gold Coast</answer>
</mchoice>
<mchoice>
<question>Launceston is the second largest city in which Australian state?</question>
<answer>Victoria</answer>
<answer>New South Wales</answer>
<answer correct="yes">Tasmania</answer>
<answer>Western Australia</answer>
</mchoice>
</quiz>
public class Question
{
public string QuestionText { get; set; }
public List<Answer> Answers { get; set; }
}
public class Answer
{
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public string Answer3 { get; set; }
public string Answer4 { get; set; }
}
我嘗試以下LINQ查詢,但我被困在回答現場
public IEnumerable<Question> GetAll()
{
var questions = from docs in _doc.Descendants("mchoice")
select new
{
QuestionText = docs.Element("question").Value,
Answers = docs.Descendants("answer").SelectMany(e=>e.Element("answer").Value)
};
return questions;
}
+1替代solution.your解決方案工作正常 –
在這種情況下可以使用Answer類嗎? –
是的,但是你將無法使用循環,並且必須在編碼時一直寫* answer1 *,* answer2 *。 –