假设如下:
- 行号
- 列号
- 一个XML文件
(其中行号和列号代表节点的'<'符号)
使用XDocument API,如何找到该位置上的XNode。
假设如下:
(其中行号和列号代表节点的'<'符号)
使用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 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);
}