Search code examples
c#xamlwindows-phone-8html-agility-pack

Windows Phone 8.0 Silverlight App & HTMLAgilityPack dealing with missing elements


Using HttpClient with HtmlAgility pack in a Windows Phone 8.0 Silverlight app.

I'd like to know how to manage an exception where an node/image isn't contained within a section of HTML.

For example, this is a snippet of the HTML I'm getting the info from.

<PARENT>
    <div class="game-c">
        <div class="boxshot">
            <img class="cover" src="http://cover_source" />
        </div>
        <h3 class="h3 white-c">Game Title ...</h3>
        <p>Game description goes here...</p>
        <p>...</p>
        <div class="cta-signedOut">...</div>
        <div class="cta-signedIn">
            <a href="https://link.to.store"> 
            <img src="gameImage.gif" /></a>
        </div>
    </div>
</PARENT>

I need the img src from the third div (cta-signedIn). However, for certain dates the last two div's are commented out. So the code looks like this:

<PARENT>
    <div class="game-c">
        <div class="boxshot">
            <img class="cover" src="http://cover_source" />
        </div>
        <h3 class="h3 white-c">Game Title ...</h3>
        <p>Game description goes here...</p>
        <p>...</p>
        **<!--<div class="cta-signedOut">...</div>
        <div class="cta-signedIn">
            <a href="https://link.to.store"> 
            <img src="gameImage.gif" /></a>
        </div-->**
    </div>
</PARENT>

Ideally, when these two div's are commented out, I would like to use my own image file which is located locally in /Assets/Images/Unavailable.png

And could you confirm that the following code would be correct to locate the info...

div.SelectSingleNode("//div[3]/a/img").Attributes["src"].Value;

Thank you.

27/03/2016 - Added following:

I'm using the following code, but it doesn't load the local image.

I'm trying the following, but it doesn't work...

var img = div.SelectSingleNode("div[@class='cta-signedIn']/a/img");
var img2 = ("/Assets/Images/storeLogo_unavailable.png");
if (img == null)
{
    newGame.StoreLink = img2;
}
else
{
    newGame.StoreLink = div.SelectSingleNode("div[@class='cta-signedIn']/a/img").Attributes["src"].Value;
}

Also, for some reason, this code executes very slowly. Any particular reason for that?


Solution

  • If you simply meant to check existence of the image and do some logic accordingly, then you can check whether SelectSingleNode() given selector for the image returns null. For example, assuming that div reference the outer div in your HTML snippet :

    var img = div.SelectSingleNode("div[@class='cta-signedIn']/a/img");
    if(img != null)
    {
        //TODO: do something with `img`
    }
    else
    {
        //TODO: use local image file
    }
    

    BTW, I suggested a possibly more meaningful selector in the snippet above. Element position index is commonly less meaningful.