Load an XElement and keep the line information in CSharp
Description
The following code shows how to load an XElement and keep the line information.
Example
using System;/*from w ww . ja v a 2s . c om*/
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);
}
}
}
The code above generates the following result.