How to get the location of an XmlElement character?

Let's say in my C # code I got an XmlElement (or XElement ) from an XmlDocument (or XDocument ). strong>). How to get the character layout of this XmlElement in an XML file?

In other words, I want to say

"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".
+3
source share
1 answer

I'm not sure if it is possible to determine the char number, but you can find the line number and position inside 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);
+4
source

All Articles