简体   繁体   中英

LINQ to XML query. Get element attribute

I can't obtain the answer attribute due to Cannot convert lambda expression to delegate type . These are my classes and my query :

var file = XDocument.Load("QuestionsTest.xml");
var questions = from answers in file.Root.Elements("Question").Elements("Answers").Elements("Answer")
                        select new Answer
                        {
                            Text = (string)answers,
                            Correct = (string)answers.Elements("Answer").Single(answer=>(string)answer.Attribute("Correct"))
                        };

public class Answer
{
    public int AnswerID { get; set; }
    public string Text { get; set; }
    public string Correct { get; set; }
    public int Stats { get; set; }

    public int QuestionID { get; set; }
}

public class Question
{
    public virtual List<Answer> Answers { get; set; }
}

My XML looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Questions Subject="ADO.NET">
  <Question  NumberOfAnswers="1">
    <Text>Which class should you use to manage multiple tables and relationships among them?</Text>
    <Answers>
      <Answer>DataRow</Answer>
      <Answer>DataView</Answer>
      <Answer>DataTable</Answer>
      <Answer Correct="Yes">DataSet</Answer>
    </Answers>
 </Question>
  </Questions>

How can I get the answer's attribute?

Enumerable.Single accepts Func<T,bool> delegate which should return boolean value. You are passing delegate which returns XAttribute value. You should compare attribute value with Yes string to return boolean result:

Single(answer => (string)answer.Attribute("Correct") == "Yes")

This will fix your error. But I think you also should change logic of your query. First change Answer class, and make Correct property boolean:

public class Answer
{
    public int AnswerID { get; set; }
    public string Text { get; set; }
    public bool IsCorrect { get; set; }
    public int Stats { get; set; }
    public int QuestionID { get; set; }
}

And query should look like:

var xdoc = XDocument.Load("QuestionsTest.xml");
var questions =
      from q in xdoc.Descendants("Question")
      select new Question {
          Answers = (from a in q.Descendants("Answer")
                     select new Answer {
                        Text = (string)a,
                        IsCorrect = (string)a.Attribute("Correct") == "Yes"
                    }).ToList()
      };
var questions = from answers in 
    file.Root.Elements("Question").Elements("Answers").Elements("Answer")
    select new Answer
    {
        Text = (string)answers,
        Correct = (string)answers.Attribute("Correct")
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM