I have the following code
const string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Revisions>
<Revision Key=""MIDTERM"">5850</Revision>
<Revision Key=""LONGTERM"">5850</Revision>
</Revisions>";
var key = "MIDTERM";
var _RevisionsXml = XDocument.Parse(xml, LoadOptions.PreserveWhitespace);
var revisionNode = _RevisionsXml
.Root
.Elements("Revision")
.FirstOrDefault(elem => elem.Attribute("Key").ToString() == key);
The revisionNode is always null, not sure what is that I am missing.
You want to use
.Valueinstead of.ToString()when comparing your key.Invoking
ToString()on the attribute will returnKey="MIDTERM", which is mostly used for debugging purpose.Be sure that your XML is well formed or you could face a
NullReferenceExceptionwhen calling.Valueif there is no attribute namedKey.