Fetch value of element by attribute using linq to xml

rilp44

New Member
I have following xml and I want to fetch the value of node which has attribute.\[code\]<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; }}\[/code\]I tried following query but I am getting null in CorrectAnswer filed\[code\]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").Valuehttp://stackoverflow.com/questions/11089900/=="yes").Select(x=>x)\[/code\]Excepted Output
  • QuestionText-What is the capital city of Australia?
  • Answer-List
  • CorrectAnswer-Canberra
 
Back
Top