LINQ to XML查询。获取元素属性

时间:2014-08-05 09:48:47

标签: c# xml linq linq-to-xml

由于Cannot convert lambda expression to delegate type,我无法获得答案属性。这些是我的课程和我的查询:

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

我的XML看起来像这样:

<?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>

如何获得答案的属性?

2 个答案:

答案 0 :(得分:1)

Enumerable.Single接受Func<T,bool>委托,该委托应返回 boolean 值。您正在传递返回XAttribute值的委托。您应属性值与Yes字符串进行比较以返回布尔结果:

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

这将解决您的错误。但我认为你也应该改变你的查询逻辑。首先更改Answer类,并使Correct属性布尔值:

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

查询应如下所示:

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

答案 1 :(得分:1)

var questions = from answers in 
    file.Root.Elements("Question").Elements("Answers").Elements("Answer")
    select new Answer
    {
        Text = (string)answers,
        Correct = (string)answers.Attribute("Correct")
    };