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

Sim*_*mon 5 c# xml linq-to-xml

鉴于以下情况

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

(其中行号和列号代表节点的“<”字符)

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

Tho*_*que 3

你可以这样做:

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();
}
Run Code Online (Sandbox Code Playgroud)