DCSIMG
LINQ to XML - XElement - Descendants vs. Elements - Zuker On Foundations

Zuker On Foundations

The realm of .NET (WPF, WCF and all around)
LINQ to XML - XElement - Descendants vs. Elements

Someone asked me what the difference between descendants and elements is, I thought I'd post the details here for common interest.

Descendants will yield you elements of your choice from the entire source element sub-tree, whereas Elements will yield the child elements only.

E.g.

 string xml = @"
                <Root>
                    <Item>
                        <id>1</id>
                    </Item>
                    <Item>
                        <id>2</id>
                    </Item>
                    <Item>
                        <id>3</id>
                        <Items>
                            <Item>
                                <id>5</id>
                            </Item>
                            <Item>
                                <id>6</id>
                            </Item>                            
                        </Items>
                    </Item>
                    <Item>
                        <id>4</id>
                    </Item>
                </Root>";

            XDocument doc1 = XDocument.Parse(xml);

            var q1 = from e in doc1.Root.Descendants("Item")
                     select e;

            var q2 = from e in doc1.Root.Elements("Item")
                     select e;

            int c1 = q1.Count(); //6
            int c2 = q2.Count(); //4

Published Thursday, January 15, 2009 3:25 PM by Amir Zuker

תגים:,

Comments

# re: LINQ to XML - XElement - Descendants vs. Elements@ Thursday, September 30, 2010 2:33 AM

Here is a better description, in my opinion:

Elements finds only those elements that are direct descendents, i.e. immediate children.

Descendants finds children at any level, i.e. children, grand-children, etc...

Mike Johnson

# re: LINQ to XML - XElement - Descendants vs. Elements@ Monday, February 07, 2011 10:27 PM

thank you!

banana

# re: LINQ to XML - XElement - Descendants vs. Elements@ Wednesday, January 25, 2012 8:44 AM

No, I think Amir has done a better job than you Mike.

Please post your web site site Mike so I can have a look at your helpful hints.

SleepyBoBos

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: