Extension Class
  • Name.LocalName.StartsWith
  • Ancestor method

Step: 1 Create new website and add the items shown in the following illustrations

Step 2 Add the codes

using System.IO;
using System;
using System.Text;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XDocument StudentList =
new XDocument(
    new XElement("Students",
            new XElement("Student",
            new XElement("Name", "David"),
            new XElement("Subject", "Chemistry"),
            new XElement("Test1","96"),
            new XElement("Test2","92")
          ),
new XElement("Student",
         new XElement("Name", "Daniel"),
         new XElement("Subject", "Chemistry"),
         new XElement("Test1", "91"),
         new XElement("Test2", "95")
         ),
new XElement("Student",
      new XElement("Name", "Peter"),
      new XElement("Subject", "Chemistry"),
      new XElement("Test1", "98"),
     new XElement("Test2", "97"))
));
StudentList.Save(@"C:\xml_linq\xmllinqextn1\Student1.xml");
L1.Text += "--<u><b>Displaying XML data StudentList.Elements('Students')</u> </b><br/>";
XElement root = StudentList.Element("Students");
IEnumerable<XElement> std = root.Elements();
GridView1.DataSource = std;
GridView1.DataBind();
IEnumerable<XElement> SecondGeneration =
from stdelem in StudentList.Descendants()
where stdelem.Name.LocalName.StartsWith("Name")
select stdelem;

L1.Text+="Great Grand Children Elements <br/>" ;
L1.Text+="----";
foreach (XElement de in SecondGeneration)
{
L1.Text+=de.Name +"<br/>";

}

IEnumerable<XElement> allAncestors =
from stdelem in SecondGeneration.Ancestors().Distinct()
select stdelem;

L1.Text+="------";
L1.Text+="Ancestors";
L1.Text+="----<br/>";
foreach (XElement de in allAncestors)
{
L1.Text+= de.Name + "<br/>";
}

}
}
 

Default.aspx

 

Step 3 Runtime analysis: note GridView serializes the data enumerated root elements , in table format. ancestor method outputs the "Student" element and where clause filters the child element "Name"