Linq to XML Descendants 和 Elements的區別


xml結構:

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

 查詢代碼:

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

由上可知,Elements不能查詢包含在其子節點中的<bar>節點的元素,它是查詢root直接所屬的一級chirden元素,而Descendants是查詢root節點下的所有的<bar>節點元素。
另外,Elements寫法繁瑣,需要從根節點元素一直往下開始寫:如root.Elements("baz").Elements("bar"),而Descendants則不需要,直接root.Descendants("name")就可以了



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM