Get Last Element in C# using XElement

前端 未结 5 913
一向
一向 2020-12-07 04:35

I have a XML feed loaded in an XElement.

The structure is





         


        
相关标签:
5条回答
  • 2020-12-07 04:57

    You can use LastNode property on root element:

    XElement root = doc.Root;
    XElement lastPost = (XElement)root.LastNode;
    
    0 讨论(0)
  • 2020-12-07 05:05
    var doc = XDocument.Parse(xml);
    var lastPost = doc.Descendants("post").Last();
    
    0 讨论(0)
  • 2020-12-07 05:09

    Or try this to get XElement:

    XDocument doc = XDocument.Load("yourfile.xml");          
    XElement root = doc.Root;
    Console.WriteLine(root.Elements("post").Last());
    
    0 讨论(0)
  • 2020-12-07 05:10

    Try this

    XDocument doc= XDocument.Load("path to xml");
    var last=doc.Root.LastNode;
    
    0 讨论(0)
  • 2020-12-07 05:12

    Try this:

    rootElement.Descendants().Last()
    

    If you aren't sure there'll be any, you could also use LastOrDefault(). If there might be other elements besides within the , there's an overload of Descendants that will let you find just the posts you're looking for.

    0 讨论(0)
提交回复
热议问题