XDocument xdoc = XDocument.Load(file);
IEnumerable<XElement> categories = xdoc.Descendants("Category");
foreach (XElement category in categories)
{
//get line number for element here...
}
答案 0 :(得分:60)
XElement
(实际上XObject
)实现了IXmlLineInfo
接口,因此您可以使用它:
IXmlLineInfo info = category;
int lineNumber = info.LineNumber;
请注意,行信息并非始终可用,您需要调用HasLineInfo
方法来检查信息是否可用。使用LoadOptions.SetLineInfo
XDocument.Load
答案 1 :(得分:29)
XDocument xdoc = XDocument.Load(file, LoadOptions.SetLineInfo);
IEnumerable<XElement> categories = xdoc.Descendants("Category");
foreach (XElement category in categories)
{
//get line number for element here...
string lineNumber = ((IXmlLineInfo)category).HasLineInfo() ? ((IXmlLineInfo)category).LineNumber : -1;
}