alexaRank = doc.Descendants("COUNTRY")
.Select(c => (int?)c.Attribute("RANK"))
.Where(r => r.HasValue)
.FirstOrDefault() ?? -1;
HOW IT WORKS: all COUNTRY
descendants are selected from xml response (no matter where these elements sit in xml). Then from each country element we select attribute RANK
and cast this attribute to nullable integer. That gives null
if country do not have rank attribute or value of this attribute. Then we select first or default value from rank attributes values. If nothing is found, then it gives us a null
. With null-coalescing operator ??
we assign -1
instead of null
. If someting is found, then value of nullable integer will be assigned to alexaRank
.
So, you will not get parsing exceptions here - if country node not found, or there is no country node with rank attribute (well, only if rank is not integer). But you still can get another exceptions, like errors if network is not available. So, you can keep try catch
here. But do not swallow exception! You should log it.
Also you can use XPath:
private int GetAlexaRank(string domain)
{
try
{
var doc = XDocument.Load(url);
var country = xdoc.XPathSelectElement("//COUNTRY[@RANK]");
if (country == null)
return 0;
return (int)country.Attribute("RANK");
}
catch (Exception e)
{
// Log exception here!
return -1;
}
}