Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving an Attribute Value from an XNode

I have my XML file loaded and then I select my last element. Here is the code:

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

The code above outputs the last element on the XML file. Here is the code:

  <link num="4" url="yahoo.com">Yahoo</link>

I want to be able to select the value 4 of num. Here is the code:

  num="4"

How can I select the number 4 from my last node?

like image 397
Mellie Segarra Avatar asked Jan 02 '26 01:01

Mellie Segarra


1 Answers

Try this:

XDocument xDoc = XDocument.Parse(xml);
string num = xDoc.Root.Elements().Last().Attribute("num").Value;
Console.WriteLine(num);

Make sure you have added the following using:

using System.Linq;
using System.Xml.Linq;
like image 197
Howard Avatar answered Jan 03 '26 17:01

Howard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!