How to get src tag from image?

c# html-agility-pack xml xpath

Question

I'm attempting to get a URL's src attribute.img tag. The issue is that I get nosrc rather than an empty string. But if I take away the//img/@src I see what's written ina tag (image). What is the issue? I came across several questions with a similar problem, but none of the solutions were satisfactory to me.

<div class="clearfix">
  <div class="container left">    
     <div class="logo">
        <a href="/teams/japan/japan/1348/">
        <img src="http://cache.images.core.optasports.com/soccer/teams/150x150/1348.png" alt="Giappone">
       </a>
     </div>
</div>

Here's my code:

var shieldHomeContainer = nodeCollection.SelectSingleNode("//div[@class='container left']//div[@class='logo']//a//img/@src");
1
0
9/1/2016 2:34:38 PM

Accepted Answer

Consider attempting this

var shieldHomeContainer = nodeCollection.SelectSingleNode("//img").Attributes["src"].Value;
3
9/1/2016 2:49:18 PM

Popular Answer

An attribute cannot be explicitly chosen. You must first choose an element before calling.GetAttributeValue() .

var h=new HtmlAgilityPack.HtmlDocument();
h.LoadHtml(@"
<div class=""clearfix"">
  <div class=""container left"">    
     <div class=""logo"">
        <a href = ""/teams/japan/japan/1348/"" >
        <img src=""something"" alt=""Giappone"">
       </a>
     </div>
</div>");
var img = h.DocumentNode.SelectSingleNode(
 "//div[@class='container left']//div[@class='logo']//a//img");
Debug.WriteLine(img.GetAttributeValue("src","nothing"));

Use if you wish to confirm if the element has that property.img[@src] .



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow