2

我是 Linq 的新手,所以对非常基本的问题表示歉意。

我有以下类型的 XML

<QuestionSet type="MCQ">
  <Question>

    What will the output of following

       // main()
       // {
        // int x = 10, y = 15;
        // x = x++;
        // y = ++y;
        // printf("%d, %d", x, y);
       // }
    </Question>"

<Options>
    <Option number="1">10, 15</Option>
    <Option number="2">10, 16</Option>
    <Option number="3">11, 15</Option>
    <Option number="4">11, 16</Option>
  </Options>
</QuestionSet>

我想通过属性 1、2、3 和 4 来获取选项值。

4

2 回答 2

2
var questions = from qs in xdoc.Descendants("QuestionSet")
                let options = qs.Element("Options").Elements()
                select new {
                  Question = (string)qs.Element("Question"),
                  Options = options.ToDictionary(o => (int)o.Attribute("number"),
                                                 o => (string)o)
                };

这将为集合中的每个问题返回匿名对象的集合。所有选项都将在以数字为键的字典中:

foreach (var question in questions)
{
    Console.WriteLine(question.Question);

    foreach (var option in question.Options)        
        Console.WriteLine("{0}: {1}", option.Key, option.Value); 

    // or ConsoleWriteLine(question.Options[2])       
}

如果您只想要此特定 xml 中的选项:

var options = xdoc.Descendants("Option")
                  .ToDictionary(o => (int)o.Attribute("number"), o => (string)o);

Console.WriteLine(options[1]); // 10, 15
于 2013-09-05T09:00:08.097 回答
1
var d = new XmlDocument();
d.LoadXml("yuor document text");

d.ChildNodes.OfType<XmlElement>().SelectMany(root => root.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Options").SelectMany(options => options.ChildNodes.OfType<XmlElement>().Select (option => option.Attributes["number"].Value))).Dump();

它可能有点敏捷。也许更好地使用 foreach 或使用 XPATH //options/option["number"] - (xpath 查询可能是错误的)

于 2013-09-05T08:51:50.513 回答