How to find XML node from row and column number in C #?

Given the following

  • Line number
  • Column number
  • XML file

(where the row and column number represents the "<" character for node)

Using the XDocument API, how to find the XNode at this position.

+4
source share
2 answers

You can do something like this:

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(); } 
+3
source

See LINQ to XML and line numbers on LINQ Exchange gives an example using IXmlLineInfo that matches what you are 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); } 
+1
source

Source: https://habr.com/ru/post/1395742/


All Articles