我有跟随xml,我想获取具有属性的节点的值。
<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<string> Answers { get; set; }
public string CorrectAnswer { get; set; }
}
我尝试了以下查询,但我在 CorrectAnswer 提交
时变为空var questions = from docs in _doc.Descendants("mchoice")
let answers = _doc.Elements("answer")
select new Question
{
QuestionText = docs.Element("question").Value,
Answers = docs.Elements("answer").Select(a => a.Value).ToList(),
CorrectAnswer=docs.Elements("answer").Where(x=>x.Attribute("correct").Value=="yes").Select(x=>x)
例外输出
答案-列表
CorrectAnswer-堪培拉
答案 0 :(得分:2)
尝试更改此行:
CorrectAnswer=docs.Elements("answer").Where(x=>x.Attribute("correct").Value=="yes").Select(x=>x)
成为:
CorrectAnswer=docs.Elements("answer")
.First(x=> x.HasAttributes && x.Attribute("correct").Value=="yes")
.Value