Using xml: How do you guard for Null Reference exceptions in Linq To Xml? on newest questions tagged xml – Stack Overflow
<?xml version="1.0" encoding="utf-8" ?>
<pages>
<page id="56">
<img id="teaser" src="img/teaser_company.png"></img>
</page>
</pages>
I have an xml file that defines additional resources for pages within a cms. What’s the best way to guard for Null Reference exceptions when querying this file with LinqToXml?
var page = (from tabElement in extensionsDoc.Descendants("page")
where tabElement.Attribute("id").Value == tabId.ToString()
select tabElement).SingleOrDefault();
This code could potentially trigger a Null Reference exception if a page element doesn’t have an attribute called “id”. Do I have to use a try catch block or is there a way to handle this? For instance return null for page the page object if there’s no attribute called “id” for the page element.
See Answers
source: http://stackoverflow.com/questions/792919/how-do-you-guard-for-null-reference-exceptions-in-linq-to-xml
Using xml: using-xml
Recent Comments