Haris
Haris

Reputation: 788

Trying to get the values of all child nodes

My XML Looks like this:

<names>
    <goodnames>
        <name>Alpha</name>
        <name>Beta</name>
    </goodnames>
    <badnames>
        <name>blabla</name>
    </badnames>
</names>

Now I am trying to get the value of all child nodes that belong to goodnames or badnames. The code I've tried so far is this:

var goodnames = from el in doc.Root.Elements("goodnames") select el.Element("name");

Unfortunately, this only returns the very first element, in this case Alpha. However, I'd like to get all the name elements.

Upvotes: 0

Views: 51

Answers (1)

Enigmativity
Enigmativity

Reputation: 117175

If you want all names you need to do this:

var allNames =
    from e in doc.Root.Descendants("name")
    select e.Value;

If you only want good names or bad names, try this kind of thing:

var goodnames =
    from el in doc.Root.Elements("goodnames")
    from n in el.Elements("name")
    select n.Value;

Upvotes: 1

Related Questions