![](/img/trans.png)
[英]How to search XML files with XPath, returning line and column number(s) of found node(s) with C#?
[英]How to find an XML node from a line and column number in C#?
鑒於以下內容
(行號和列號表示節點的“<”字符)
使用XDocument API如何在該位置找到XNode。
你可以這樣做:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.