假设在我的C#代码中,我从 XmlDocument (或 XDocument >中检索到了 XmlElement (或 XElement ) STRONG>)。如何在XML文件中获取此XmlElement的字符位置?
换句话说,我想被告知
"Your element starts on the 176th character in the text file containing the XML",
不是
"Your 'book' element is the 3rd 'book' element in the whole XML document".
答案 0 :(得分:4)
我不确定这是否可以确定字符编号,但您可以在该行内找到行号和位置:
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);