podeig
podeig

Reputation: 2741

How to get first level of children by LINQ

I have such XMl

<root>
    <list>
        <list>
            <topic></topic>
            <topic></topic>
        </list>
        <topic></topic>
        <topic></topic>
    </list>
    <topic></topic>
    <topic></topic>
    <topic></topic>
</root>

I need to get the first level of children:

<list></list>
<topic></topic>
<topic></topic>
<topic></topic>

I try to do like this

var list = x.Descendants().Where(e => e.Name == "list" || e.Name == "topic");

But it returns all topics and lists.

Please help! :)

Upvotes: 19

Views: 10998

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500835

Just document.Root.Elements() should work.

Basically Descendants() recurses, whereas Elements() only gets direct children.

Upvotes: 49

Related Questions