Mega Code Archive

 
Categories / C# / XML LINQ
 

Query Descendants And Self

using System; using System.IO; using System.Xml; using System.Linq; using System.Xml.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {     public static void Main()     {         string markup =         @"<Root>             <Child>                 <GrandChild/>             </Child>         </Root>";         using (XmlReader nodeReader = XmlReader.Create(new StringReader(markup)))         {             nodeReader.MoveToContent();             XDocument xRoot = XDocument.Load(nodeReader, LoadOptions.SetLineInfo);             foreach (XElement e in xRoot.Elements("Root").DescendantsAndSelf())                 Console.WriteLine("{0}{1}{2}",                     ("".PadRight(e.Ancestors().Count() * 2) + e.Name),                     ((IXmlLineInfo)e).LineNumber,                     ((IXmlLineInfo)e).LinePosition);         }     } }