如何从C#中的行号和列号中查找XML节点

本文关键字:查找 节点 XML | 更新日期: 2023-09-27 18:24:05

给定以下

  • 一个行号
  • 列编号
  • XML文件

(其中行号和列号表示节点的"<"字符)

使用XDocumentneneneba API如何找到该位置的XNode。

如何从C#中的行号和列号中查找XML节点

您可以这样做:

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

请参阅LINQ to XML和LINQ Exchange上的行号,给出了一个使用IXmlLineInfo的示例,该示例与您要查找的内容相对应:

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