It specifies the
starting point of the ancestor search. As you have learned in the last few chapters, you could have just as
easily done the following, but the question is, would the results be the same?
161
Part II: LINQ to XML
IEnumerable
anc = root.Element("Employee").Elements("Name");
foreach (XElement el in anc.Ancestors())
listBox1.Items.Add(el.Name);
There really is no advantage of using one approach over the other. The Ancestors method returns an
IEnumerable XEelement of all the ancestors of the current Element. As you will find out in the next
section, the Descendants method returns an IEnumerable XElement of all the descendants of the current
Element. So, it really depends on how you want to approach the problem.
The Ancestors method also has an overload that takes an element name, returning only those elements
in the collection that match the specified name. For example, the following returns a collection filtered by
the ancestor elements that have a matching XName (element name):
XElement root = new XElement("Employees",
new XElement("Employee",
new XElement("Name", "Scott")
)
);
IEnumerable anc = root.
Pages:
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281