2014-02-07 143 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();