Linq to XML 后代和元素有什么区别 [英] What is the difference between Linq to XML Descendants and Elements
问题描述
我在 VS IntelliSense 中遇到过这两个关键字.我试图用谷歌搜索它们之间的区别,但没有得到明确的答案.其中哪一个对中小型 XML 文件具有最佳性能.谢谢
Elements
只找到那些直接后代的元素,即直接的孩子.
Descendants
级别,即子代、孙代等...
这是一个演示差异的示例:
代码:
XDocument doc = XDocument.Load("input.xml");XElement 根 = doc.Root;foreach (XElement e in root.Elements("bar")){Console.WriteLine("元素:" + e.Value);}foreach (XElement e in root.Descendants("bar")){Console.WriteLine("后代:" + e.Value);}
结果:
<前>元素:测试 1元素:测试 3后代:测试1后代:测试2后代:测试3如果您知道您想要的元素是直接子元素,那么如果您使用 Elements
而不是 Descendants
,您将获得更好的性能.
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:
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
.
这篇关于Linq to XML 后代和元素有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!