Mega Code Archive

 
Categories / C# / XML LINQ
 

XDocument Load(XmlReader, LoadOptions) loads an XElement from an XmlReader with option

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).PadRight(20),                     ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5),                     ((IXmlLineInfo)e).LinePosition);         }     } }