Descendants("Name");
foreach (XElement el in anc.Ancestors("Employee"))
listBox1.Items.Add(el.Name);
The code returns the following value:
Employee
The same thing happens even if an additional employee is added, as shown here:
XElement root = new XElement("Employees",
new XElement("Employee",
new XElement("Name", "Scott")),
new XElement("Employee",
new XElement("Name", "Bob"))
);
IEnumerable
anc = root.Descendants("Name");
foreach (XElement el in anc.Ancestors("Employee"))
listBox1.Items.Add(el.Name);
Now the code returns the following values:
Employee
Employee
You are probably asking yourself, ??????How is this useful???™??™ While these examples may seem trivial, the
methods (Ancestors, Descendants, and so on) return an IEnumerable collection??”meaning that they
return a collection of elements, in this case a collection of Employee elements. These examples just
162
Chapter 8: Advanced LINQ to XML Programming Topics
displayed the name of the element, but you do so much more, such as grabbing the values of the elements
as you loop through the collection, like this:
foreach (XElement el in anc.
Pages:
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282