what does Descendants keyword does in LINQ ? RRS feed

  • Question

  • User264732274 posted

    what Descendants keyword does ?

    can we omit this ? please write in details with example to understand the usage of Descendants keyword. thanks

    var items = xmldoc.Descendants("whatevernodename")
               .Select(node => node.Value.ToString())
    Sunday, July 19, 2015 8:29 AM


  • User61956409 posted

    Hi sudip_inn,

    what Descendants keyword does ?

    XDocument.Descendants method could returns a collection of the descendant elements for this document or element, in document order. It has two overloads Descendants() and Descendants(XName). For more information, please refer to this link.


    Besides, this sample is for your reference.


    <?xml version="1.0" encoding="utf-8" ?>
      <employee id ="1" name="emp1"  designation="Managing Director" company="comp1">emp1</employee>
      <employee id ="2" name="emp2"  designation="Team Leader (S/W)" company="comp2">emp2</employee>
      <employee id ="3" name="emp3"  designation="Managing Director" company="comp1">emp3</employee>

    Web page

        <asp:Button ID="btnfind" runat="server" Text="Find Descendant Elements " OnClick="btnfind_Click" />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    protected void btnfind_Click(object sender, EventArgs e)
        XDocument xmldoc = XDocument.Load(Server.MapPath("Data/EmployeesInfo.XML"));
        var items = xmldoc.Descendants("employee").Select(node => node.Value.ToString()).ToList();
        GridView1.DataSource = items;

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2015 4:00 AM