以XML后代和LINQ的元素之间的区别是什么后代、元素、区别、XML

2023-09-02 20:43:33 作者:九亿少女的梦

我已经跨越了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.