Get Attribute Value by LINQ

getelementbyid html-agility-pack linq

Question

Here is the HTML source code:

<img id="itemImage" src="https://www.xyz.com/item1.jpg">

To get the SRC value, the following LINQ query is being used (Image Link)

string imageURL = document.DocumentNode.Descendants("img")
                    .Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
                    .Select(node => node.Attributes["src"].Value).ToString();

However, imageURL produces output as

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String]
1
0
2/7/2014 9:15:33 AM

Accepted Answer

Casting it to string is the issue.Select() returns IEnumerable<T> Consequently, you are essentially turning an enumerator into a string (as the error message says). CallFirst() or Single() or Take(1) before converting it to a string, in order to get a single element.

.Select(node => node.Attributes["src"].Value).First().ToString();

Additionally, if there's a risk the required component won't be there,FirstOrDefault() and SingleOrDefault() instead of throwing an exception, returns nil. If that's the case, I suggest

var imageUlr = ... .Select(node => node.Attributes["src"].Value).FirstOrDefault();
if (imageUrl != null)
{
    // cast it to string and do something with it
}
2
2/7/2014 9:18:10 AM

Popular Answer

.DefaultIfEmpty(string.Empty) should be included. FirstOrDefault

string imageURL = document.DocumentNode.Descendants("img")
                .Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
                .Select(node => node.Attributes["src"].Value)
                .DefaultIfEmpty(string.Empty)
                .FirstOrDefault()
                .ToString();


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