0

I'm having a bit of a problem parsing one specific value from an XML document. The code I'm using is as follows:

WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
XElement root = doc.Root;
ClassVars.LastTimeStamp = (int)root.Elements("TIMESTAMP").Last();

However, this code is generating the following exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll

(the full error message is here.)

And to be quite frank, I can't figure out for the life of me why. The line which it errors on is the ClassVars.LastTimeStamp = (int)root.Elements("TIMESTAMP").Last(); line. I'm trying to parse this from the following XML:

<REGION>
<MESSAGES>
<POST>
<TIMESTAMP>1439137652</TIMESTAMP>
<NATION>...</NATION>
<MESSAGE>
</MESSAGE>
</POST>
...
...
...
<POST>
<TIMESTAMP>1439137856</TIMESTAMP>
<NATION>...</NATION>
<MESSAGE>
...
</MESSAGE>
</POST>
</MESSAGES>
</REGION>

What I want to do is extract the TIMESTAMP from the last POST in the file. Can someone tell me what I'm doing wrong? It's probably blindingly obvious, but I just don't see it.

3
  • Could you paste the error message? Commented Aug 9, 2015 at 18:40
  • @Douglas: too long for a comment, see pastebin.com/sKP4jFZ2 Commented Aug 9, 2015 at 18:46
  • @TaW I'm so stupid, so sorry! I was still using a test key in my WebRequest. Thanks for making me realise hehe! Commented Aug 9, 2015 at 19:04

2 Answers 2

4

The issue is that you're using the wrong method for retrieving the <TIMESTAMP> elements. XElement.Elements only returns child elements. In your case, <TIMESTAMP> is three levels deep, so you need to use Descendants instead.

ClassVars.LastTimeStamp = (int)root.Descendants("TIMESTAMP").Last();
Sign up to request clarification or add additional context in comments.

3 Comments

I think a better alternative is learning XPath and giving the path to the child element. It's a much more stable solution.
@GreĝRos: I agree that would be better discipline, especially if path validation is important. On the other hand, it might be that the OP doesn't care about the exact XML structure, and wants code that will still work if the structure changes.
@Douglas is correct - I'm using an API which does change a fair deal, and I don't really care about the structure - I just need to parse that one bit as a variable in my code.
1

Assuming that this is the entire doc (except for the header), REGION is the only element of root. Try using Descendants instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.