2

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.

Omkar Khair
  • 1,364
  • 2
  • 17
  • 40

5 Answers5

8

Or try this to get XElement:

XDocument doc = XDocument.Load("yourfile.xml");          
XElement root = doc.Root;
Console.WriteLine(root.Elements("post").Last());
Tassisto
  • 9,877
  • 28
  • 100
  • 157
ductran
  • 10,043
  • 19
  • 82
  • 165
2

You can use LastNode property on root element:

XElement root = doc.Root;
XElement lastPost = (XElement)root.LastNode;
Tu Tran
  • 1,957
  • 1
  • 27
  • 50
1
var doc = XDocument.Parse(xml);
var lastPost = doc.Descendants("post").Last();
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
0

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.

Mr. Putty
  • 2,276
  • 1
  • 20
  • 20
0

Try this

XDocument doc= XDocument.Load("path to xml");
var last=doc.Root.LastNode;
Tariqulazam
  • 4,535
  • 1
  • 34
  • 42