HtmlAgilityPack HasAttribute? [英] HtmlAgilityPack HasAttribute?

查看:93
本文介绍了HtmlAgilityPack HasAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想做

node.Attributes["class"].Value

但是,如果节点没有class属性,则会崩溃.所以,我必须首先检查它的存在,对吗?我怎么做? Attributes不是dict(它包含内部dict ??的列表),并且没有HasAttribute方法(只是一个HasAttributes指示它是否具有任何属性).我该怎么办?

But if the node doesn't have the class attribute, it crashes. So, I have to check for its existence first, right? How do I do that? Attributes is not a dict (its a list that contains an internal dict??), and there's no HasAttribute method (just a HasAttributes which indicates if it has any attribute at all). What do I do?

推荐答案

更新后的答案

如果缺少属性,请使用node.Attributes["class"]?.Value返回null.这与下面的ValueOrDefault()相同.

Use node.Attributes["class"]?.Value to return null if the attribute is missing. This will be the same as the ValueOrDefault() below.

原始答案

尝试一下:

String val;
if(node.Attributes["class"] != null)
{
  val = node.Attributes["class"].Value;
}

或者您可以添加此

public static class HtmlAgilityExtender
{
    public static String ValueOrDefault(this HtmlAttribute attr)
    {
        return (attr != null) ? attr.Value : String.Empty;
    }
}

然后使用

node.Attributes["class"].ValueOrDefault();

我还没有测试过,但是应该可以.

I havent tested that one, but it should work.

这篇关于HtmlAgilityPack HasAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆