Given the following
- A line number
- A column number
- An XML file
(Where the line and column number represent the '<' character of a node)
Using the XDocument API how do I find the XNode at that position.
Given the following
(Where the line and column number represent the '<' character of a node)
Using the XDocument API how do I find the XNode at that position.
You can do something like that:
XNode FindNode(string path, int line, int column)
{
XDocument doc = XDocument.Load(path, LoadOptions.SetLineInfo);
var query =
from node in doc.DescendantNodes()
let lineInfo = (IXmlLineInfo)node
where lineInfo.LineNumber == line
&& lineInfo.LinePosition <= column
select node;
return query.LastOrDefault();
}
See LINQ to XML and Line Numbers on LINQ Exchange gives an example using IXmlLineInfo that corresponds to what you're looking for:
XDocument xml = XDocument.Load(fileName, LoadOptions.SetLineInfo);
var line = from x in xml.Descendants()
let lineInfo = (IXmlLineInfo)x
where lineInfo.LineNumber == 21
select x;
foreach (var item in line)
{
Console.WriteLine(item);
}