gpt4 book ai didi

c# - HtmlAgilityPack 有属性吗?

转载 作者:太空狗 更新时间:2023-10-29 18:11:23 26 4
gpt4 key购买 nike

我想做的就是

node.Attributes["class"].Value

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

最佳答案

更新的答案

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

原始答案

试试这个:

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();

我还没有测试过那个,但它应该可以工作。

关于c# - HtmlAgilityPack 有属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4090200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com