Krishan
Krishan

Reputation: 417

How to get value of element via attribute in Linq

I am new to Linq so apologies for very basic question.

i have following kind of 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>

I want to get the option values by attributes say 1, 2 , 3 and four.

Upvotes: 2

Views: 754

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

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

That will return collection of anonymous objects for each question in set. All options will be in a dictionary with number as key:

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

If you just want options from this particular xml:

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

Console.WriteLine(options[1]); // 10, 15

Upvotes: 2

Vladimir Shmidt
Vladimir Shmidt

Reputation: 2691

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

It could be a little bit agly. Maybe better to use foreach's or use XPATH //options/option["number"] - (xpath query may be wrong)

Upvotes: 1

Related Questions