How to find an XML node from a line and column num

2019-02-18 07:31发布

问题:

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.

回答1:

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


回答2:

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);
}