Omkar Khair
Omkar Khair

Reputation: 1384

Get Last Element in C# using XElement

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.

Upvotes: 2

Views: 14288

Answers (5)

ductran
ductran

Reputation: 10203

Or try this to get XElement:

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

Upvotes: 9

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35136

var doc = XDocument.Parse(xml);
var lastPost = doc.Descendants("post").Last();

Upvotes: 1

Tariqulazam
Tariqulazam

Reputation: 4585

Try this

XDocument doc= XDocument.Load("path to xml");
var last=doc.Root.LastNode;

Upvotes: 0

Mr. Putty
Mr. Putty

Reputation: 2316

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.

Upvotes: 0

Tu Tran
Tu Tran

Reputation: 1977

You can use LastNode property on root element:

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

Upvotes: 2

Related Questions