3

I have got a xml file which looks like this:

<events>
    <event id="12345">
        <option href="1"></option>
        <option href="2"></option>
        <option href="3"></option>
        <option href="4"></option>
    </event>
</events>

I am trying to select a pair of information from these nodes: the event id (12345) and the attribute of the elements option

var nodeWithOptions = from n in xml.Descendants("event")
                      select new
                      {
                           id = n.Attribute("id").Value,
                           options = n.Elements("option").Attributes("href").ToString(),
                      };

unfortunately this produces the following for options inside my foreach-loop: item.options = "System.Xml.Linq.Extensions+d__8"

What I want is: 12345, 1234 (yes I do not mind if the attribute value of the 4 option elements are in one string. And I also cannot change the xml file and I would prefer to use only linq.

1 Answer 1

2
var nodeWithOptions = from n in xml.Descendants("event")
                      select new
                      {
                           id = (string)n.Attribute("id"),
                           options = n.Elements("option")
                                      .Select(x => (string)x.Attribute("href"))
                                      .ToList(),
                      };

This will you List<string> with values of href attribute on option elements under given event element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.