2014-02-07 151 views
0
屬性值

HTML源代碼如下所示獲得通過LINQ

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

我使用下面的LINQ查詢來獲取SRC值(圖片鏈接)

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

但IMAGEURL給輸出

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String] 

回答

2

問題是將其轉換爲字符串。 Select()返回IEnumerable<T>因此,您基本上將枚舉數轉換爲字符串(如錯誤消息所示)。調用First()Single()Take(1)以便在將其轉換爲字符串之前獲取單個元素。

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

此外,如果有這樣的可能性:所期望的元素不存在,而不是FirstOrDefault()SingleOrDefault()返回NULL拋出異常。在這種情況下,我會建議

var imageUlr = ... .Select(node => node.Attributes["src"].Value).FirstOrDefault(); 
if (imageUrl != null) 
{ 
    // cast it to string and do something with it 
} 
0

嘗試增加FirstOrDefault()

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

添加.DefaultIfEmpty(的String.Empty) .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();