Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code> alexaRank = doc.Descendants("COUNTRY") .Select(c =&gt; (int?)c.Attribute("RANK")) .Where(r =&gt; r.HasValue) .FirstOrDefault() ?? -1; </code></pre> <p>HOW IT WORKS: all <code>COUNTRY</code> descendants are selected from xml response (no matter where these elements sit in xml). Then from each country element we select attribute <code>RANK</code> and cast this attribute to nullable integer. That gives <code>null</code> 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 <code>null</code>. With null-coalescing operator <code>??</code> we assign <code>-1</code> instead of <code>null</code>. If someting is found, then value of nullable integer will be assigned to <code>alexaRank</code>.</p> <p>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 <code>try catch</code> here. But do not swallow exception! You should log it.</p> <p>Also you can use XPath:</p> <pre><code>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; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload