Get Last Element in C# using XElement

13,079

Solution 1

Or try this to get XElement:

XDocument doc = XDocument.Load("yourfile.xml");          
XElement root = doc.Root;
Console.WriteLine(root.Elements("post").Last());

Solution 2

You can use LastNode property on root element:

XElement root = doc.Root;
XElement lastPost = (XElement)root.LastNode;

Solution 3

var doc = XDocument.Parse(xml);
var lastPost = doc.Descendants("post").Last();
Share:
13,079
Omkar Khair
Author by

Omkar Khair

Technology Enthusiast. Exploring Cloud, IOT and Distributed/Decentralized tech.

Updated on June 30, 2022

Comments

  • Omkar Khair
    Omkar Khair almost 2 years

    I have a XML feed loaded in an XElement.

    The structure is

    <root>
    <post></post>
    <post></post>
    <post></post>
    <post></post>
    .
    .
    .
    .
    <post></post>
    </root>
    

    I want to directly get the value of the Last post. How I do that using XElement in C#.

    Thanks.