How to get src tag from image?

c# html-agility-pack xml xpath

Question

I'm trying to get the src property from an img tag. The problem's that I get no src of the image, but an empty string. Instead if I remove the //img/@src I see the content of a tag (image). What's the problem? I saw other similar question, but no solution provided working for 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>

this is my code:

var shieldHomeContainer = nodeCollection.SelectSingleNode("//div[@class='container left']//div[@class='logo']//a//img/@src");

Accepted Answer

try something like this

var shieldHomeContainer = nodeCollection.SelectSingleNode("//img").Attributes["src"].Value;

Popular Answer

You can't select an attribute directly. You need to select an element and then call 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"));

If you want to make sure that the element has that attribute, use img[@src].




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why