我想做的就是
node.Attributes["class"].Value
但如果节点没有class
属性,就崩溃了。所以,我必须先检查它是否存在,对吧?我怎么做?Attributes
不是一个字典(它是一个包含内部字典的列表??),并且没有 HasAttribute 方法(只是一个 HasAttributes 指示它是否有任何属性)。我该怎么办?
更新的答案
Use node.Attributes["class"]?.Value
回来null
如果该属性丢失。这将与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();
我还没有测试过这个,但它应该可以工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)