Reputation: 2589
I need to check if an XElement exists in the xml file. The code below throws an exception so I don't know yet how to solve it.
XDocument doc1 = XDocument.Load(@filePath);
XElement arrivalInstructions = doc1.Descendants("arrivalInstructions").First();
if (arrivalInstructions == null)
{ here I would put the code to create the XElement but it never gets here }
I've also tried this but didn't work either
XElement xml = XElement.Load(@filePath);
XElement configuration = xml.Element("Root");
var xxx = configuration.Element("arrivalInstructions");
if (xxx == null)
{ here I would put the code to create the XElement but it never gets here }
Upvotes: 0
Views: 1153
Reputation: 101701
Use FirstOrDefault
instead of First
.It doesn't throw exception if there is no item, it just returns null.
Upvotes: 1