LINQ to XML axis methods enable you to work with nodes instead of individual elements and attributes,
providing the capability to return collections of elements and attributes. This lets developers work at a
finer level of detail. This section explores a few of the main axis methods of the XElement class:
??‘ Ancestors
??‘ Descendants
??‘ AncestorsAndSelf
??‘ DescendantsAndSelf
??‘ ElementsAfterSelf
??‘ ElementsBeforeSelf
Ancestors
The Ancestors method returns the ancestor elements of the specified node. In the following example,
the ancestors (those elements above the specified element) of the Name element are returned. As stated
earlier, this method returns an IEnumerable of XElement, and the results can be enumerated through as
shown here:
XElement root = new XElement("Employees",
new XElement("Employee",
new XElement("Name", "Scott")
)
);
IEnumerable
anc = root.Descendants("Name");
foreach (XElement el in anc.Ancestors())
listBox1.Items.Add(el.Name);
The ancestor nodes of the specified node (in this case, the Name node) are returned:
Employee
Employees
The Descendants method, which will be discussed next, is also used in this example.
Pages:
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280