Element("Employee").AncestorsAndSelf();
foreach (XElement el in des)
listBox1.Items.Add(el.Name);
Either way, the results are the same. The current node plus its ancestors are returned in the results.
Emmployee
Employees
Yep, pretty simple, but efficient.
DescendantsAndSelf
The DescendantsAndSelf method is almost identical to the Descendants method; it varies only in that it
returns the current element along with its descendants. The following example constructs a simple XML
tree, and then queries the XML for the Employee node and its descendant nodes.
XElement root = new XElement("Employees",
new XElement("Employee",
new XElement("Name", "Scott"))
);
textBox1.Text = root.ToString();
IEnumerable
des =
from el in root.Element("Employee").DescendantsAndSelf()
select el;
foreach (XElement el in des)
listBox1.Items.Add(el.Name);
Equally, you could also do the following:
IEnumerable des = root.Element("Employee").DescendantsAndSelf();
foreach (XElement el in des)
listBox1.Items.Add(el.Name);
Both of these methods return the same results:
Employee
Name
165
Part II: LINQ to XML
Also, both the AncestorsAndSelf and DescendantsAndSelf methods have an overload that returns
an IEnumerable of only the elements of the name specified in the method, as shown below in the
following example:
IEnumerable des =
from el in root.
Pages:
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286