【问题标题】:How to find an XML node from a line and column number in C#?如何从 C# 中的行号和列号中查找 XML 节点?
【发布时间】:2012-02-10 10:14:54
【问题描述】:

鉴于以下

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

(其中行号和列号代表节点的'

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

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    你可以这样做:

    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】:

      请参阅 LINQ Exchange 上的 LINQ to XML and Line Numbers 给出了一个使用 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);
      }
      

      【讨论】:

      • @KenWhite 好的。已更新以包含从文章中复制的相关代码块。
      猜你喜欢
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多