0

I have following xml and I want to fetch the value of node which has attribute.

<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; }

}

I tried following query but I am getting null in CorrectAnswer filed

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)

Excepted Output

  • QuestionText-What is the capital city of Australia?
  • Answer-List

  • CorrectAnswer-Canberra

0

1 Answer 1

2

Try changing this line:

CorrectAnswer=docs.Elements("answer").Where(x=>x.Attribute("correct").Value=="yes").Select(x=>x)

To be:

CorrectAnswer=docs.Elements("answer")
   .First(x=> x.HasAttributes && x.Attribute("correct").Value=="yes")
   .Value
Sign up to request clarification or add additional context in comments.

2 Comments

Just one question.Why you apply First extension method?
Because your Where().Select() returns a list and you want just the value. Actually should put .Value after the First(), I'll edit answer, since you probably just want the text and not the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.