通过LINQ获取属性值

时间:2014-02-07 09:15:34

标签: linq html-agility-pack getelementbyid

HTML源如下

<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]

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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();

答案 2 :(得分: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();