get line number for XElement here

前端 未结 2 862
萌比男神i
萌比男神i 2020-11-27 22:20
XDocument xdoc = XDocument.Load(file);
IEnumerable categories = xdoc.Descendants(\"Category\");
foreach (XElement category in categories)
{
    //get         


        
相关标签:
2条回答
  • 2020-11-27 22:46

    XElement (actually XObject) implements the IXmlLineInfo interface, so you can use it:

    IXmlLineInfo info = category;
    int lineNumber = info.LineNumber;
    

    Note that line information is not always available, you need to call the HasLineInfo method to check if the information is available. You can specify LoadOptions.SetLineInfo when you load the document with XDocument.Load

    0 讨论(0)
  • 2020-11-27 22:55
    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;
    }
    
    0 讨论(0)
提交回复
热议问题