以XML后代和LINQ的元素之间的区别是什么 [英] What is the difference between Linq to XML Descendants and Elements

查看:182
本文介绍了以XML后代和LINQ的元素之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经跨越了VS智能感知这两个关键字来了。我试图使用Google它们之间的区别,并没有得到明确的答案。这些哪一个与小的最佳性能中等的XML文件。谢谢

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, i.e. immediate children.

后代 发现孩子任何级别,即儿童,盛大的孩子,等等...

Descendants finds children at any level, i.e. 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:

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);
}

结果:


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.

这篇关于以XML后代和LINQ的元素之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆