【问题标题】:LINQ to XML nested elements queryLINQ to XML 嵌套元素查询
【发布时间】:2014-08-04 06:31:14
【问题描述】:

我有以下 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 查询示例,但找不到我的问题。非常感谢。

【问题讨论】:

  • 这不是 Linq to SQL
  • 对不起。我的意思是 XML。我更改了标题和标签。

标签: c# xml linq


【解决方案1】:

只要改变这个:

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

【讨论】:

  • 哦,我要求.Element("Answer") 两次.. 就是这样。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
相关资源
最近更新 更多