简体   繁体   中英

What is the difference between Linq to XML Descendants and Elements

I have came across both these keywords in the VS IntelliSense. I tried to googling the difference between them and did not get a clear answer. Which one of these have the best performance with small to medium XML files. Thanks

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

Descendants finds children at any level, ie children, grand-children, etc...


Here is an example demonstrating the difference:

<?xml version="1.0" encoding="utf-8" ?>
<foo>
    <bar>Test 1</bar>
    <baz>
        <bar>Test 2</bar>
    </baz>
    <bar>Test 3</bar>
</foo>

Code:

XDocument doc = XDocument.Load("input.xml");
XElement root = doc.Root;

foreach (XElement e in root.Elements("bar"))
{
    Console.WriteLine("Elements : " + e.Value);
}

foreach (XElement e in root.Descendants("bar"))
{
    Console.WriteLine("Descendants : " + e.Value);
}

Result:

Elements : Test 1
Elements : Test 3
Descendants : Test 1
Descendants : Test 2
Descendants : Test 3

If you know that the elements you want are immediate children then you will get better performance if you use Elements instead of Descendants .

Descendants将搜索当前元素的整个子树以获取指定的名称(如果未提供名称,则将返回树的扁平版本),而Elements仅搜索当前元素的直接子元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM