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

后端 未结 2 366
深忆病人
深忆病人 2021-01-14 00:59

Given the following

  • A line number
  • A column number
  • An XML file

(Where the line and column number represent the \'<\' charact

相关标签:
2条回答
  • 2021-01-14 01:22

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 01:36

    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();
    }
    
    0 讨论(0)
提交回复
热议问题