簡體   English   中英

LINQ to XML嵌套元素查詢

[英]LINQ to XML nested elements query

我有以下Questions.xml文件

<?xml version="1.0" encoding="utf-8" ?>
<Questions>
  <Question>
    <Subject>ADO.NET</Subject>
    <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>DataSet</Answer>
    </Answers>
  </Question>
</Questions>

我想解析。 以下是我的課程和查詢。

public class Question
    {
        public string Text { get; set; }
        public string Subject { get; set; }

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

    public class Answer
    {
        public string Text { get; set; }
    }

    static void readQuestions()
    {
        var questions = from question in XDocument.Load("Questions.xml").Descendants("Questions").Elements("Question")
                        select new Question
                        {
                            Subject = (string)question.Element("Subject"),
                            Text = (string)question.Element("Text"),
                            Answers = new List<Answer>(
                                from answers in question.Elements("Answers").Elements("Answer")
                                select new Answer
                                {
                                    Text = (string)answers.Element("Answer")
                                })
                        };

        foreach (var question in questions)
        {
            Console.WriteLine("Subject: {0}\n Text: {1}", question.Subject, question.Text);
            foreach (var answer in question.Answers)
                Console.WriteLine("Answer: {0}", answer.Text);
        }
    }

問題是它沒有打印答案文本。 我搜索了不同的嵌套linq to xml查詢示例,但找不到我的問題所在。 非常感謝。

只需更改此:

XDocument.Load("Questions.xml").Descendants("Questions").Elements("Question")

至:

XDocument.Load("Questions.xml").Descendants("Question")

要么:

XDocument.Load("Questions.xml").Root.Elements("Question")

同時更改您的答案查詢:

from answers in question.Element("Answers").Elements("Answer")
select new Answer
        {
              Text = (string)answers
        })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM