XElement element = XElement.Parse(xmlString); IEnumerableancestors = element.Ancestors(); foreach (XElement ancestor in ancestors) { Console.WriteLine(ancestor.Name); }
XElement element = XElement.Parse(xmlString); IEnumerableThis code example does the same as the previous example, but this time it filters the ancestors collection by the name of the ancestor element. In this case, it only retrieves ancestors with the name "Root". Both examples use the System.Xml.Linq package library, which provides classes for working with XML documents and fragments.ancestors = element.Ancestors("Root"); foreach (XElement ancestor in ancestors) { Console.WriteLine(ancestor.Name); }