[英]How to find an XML node from a line and column number in C#?
Given the following 鉴于以下内容
(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. 使用XDocument API如何在该位置找到XNode。
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: 请参阅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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.