如何通过Linq中的属性获取元素的值

时间:2013-09-05 07:02:02

标签: c# xml linq xml-parsing

我是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来获取选项值。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 //选项/选项[“数字”] - (xpath查询可能是错误的)

相关问题