简体   繁体   中英

How to find an XML node from a line and column number in C#?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM