Reputation: 53
I am trying to get the value of the id last booking in an xml-file.
This is my code:
XElement id = (from p in z.Elements("booking")
select p.Element("id")).Last();
However this returns the tags aswell: 5 Any idea how to get the value without the -tags?
the xml-file looks soemthing like this:
<?xml version="1.0" encoding="utf-8"?>
<bookings>
<booking>
<id>1</id>
<name>a</name>
</booking>
<booking>
<id>2</id>
<name>b</name>
</booking>
</bookings>
Upvotes: 0
Views: 1383
Reputation: 11955
If there will always be at least one booking, then you should get a value for the id. If there can be no id's in the file (hence no bookings) then id will be ""
or string.Empty
depending how you like referring to an empty string.
string id = (string)z.Descendants("id").LastOrDefault();
Upvotes: 0
Reputation: 53958
Try this one:
XElement lastElement = (from p in doc.Elements("bookings").Elements("booking")
select p.Element("id")).LastOrDefault();
if(lastElement!=null)
var value = lastElement.Value;
I suppose that doc
is the object that represents you xml.
Before the code I wrote above, you should have declared this
XDocument doc = XDocument.Load("test.xml");
I supposed that the name of the xml file is test.xml.
Upvotes: 2