Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the character location of a XmlElement?

Let's say in my C# code I have retrieved a XmlElement (or XElement) from a XmlDocument (or XDocument). How do I get the character location of this XmlElement in the XML file?

In other words, I want to be told

"Your element starts on the 176th character in the text file containing the XML", 

not

"Your 'book' element is the 3rd 'book' element in the whole XML document".
like image 717
Silly Dude Avatar asked Jun 08 '11 01:06

Silly Dude


1 Answers

I'm not sure if this is possible to determine the char number, but you can find line number and position inside of the line:

var document = XDocument.Load(fileName, LoadOptions.SetLineInfo);
var element = document.Descendants("nodeName").FirstOrDefault();
var xmlLineInfo = (IXmlLineInfo)element;
Console.WriteLine("Line: {0}, Position: {1}", xmlLineInfo.LineNumber, xmlLineInfo.LinePosition);
like image 190
Alex Aza Avatar answered Nov 15 '22 15:11

Alex Aza