HtmlAgilityPack是否有属性?

9

All I want to do is

node.Attributes["class"].Value

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

3
您确定检查 node.Attributes["class"] 是否返回 null 吗? - Kirk Woll
@Kirk:你说得对...我以为它会因为某些原因抛出异常。好主意。 - mpen
4个回答

19

更新的答案

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

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


希望他们能够实现类似于val = node.Attributes["class"].Value ??? "";这样的东西,如果你根本不在意任何地方的空值... - Doggett
2
@Doggett,你可以创建一个IfNotNull扩展方法,它允许node.Attribute["class"].IfNotNull(x => x.Value)。虽然不完全符合你的要求,但我经常用它来解决这种问题。 - Kirk Woll
2
@Kirk 不错,从没想过这个,而且刚刚注意到你可以使它完全通用,以便适用于任何类型.. 很酷 :) 但仍然希望有类似的??? 或其他东西 ;) - Doggett
实际上已经有一个GetAttributeValue方法了...不需要再添加另一个。 - mpen
应该可以了: string classValue = node.Attributes["className"]?.Value; - CodeBon

3
请尝试这个:
String abc = String.Empty;     
      if (tag.Attributes.Contains(@"type"))
      {
          abc = tag.Attributes[@"type"].Value;
      }

0

这段代码可以用来获取两个 script 标签之间的所有文本。

String getURL(){
return @"some site address";
}
List<string> Internalscripts()
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlWeb().Load((@"" + getURL()));
        //Getting All the JavaScript in List
        HtmlNodeCollection javascripts = doc.DocumentNode.SelectNodes("//script");
        List<string> scriptTags = new List<string>();
        foreach (HtmlNode script in javascripts)
        {
            if(!script.Attributes.Contains(@"src"))
            {
                scriptTags.Add(script.InnerHtml);
            }
        }
        return scriptTags;
    }

0

HTML Agility Pack具有检查节点是否具有特定类或提供所有类列表的功能。

    //Select nodes example, get all <p> tag nodes and check if they have a class and if they do, get the class attribute.
foreach (HtmlNode node in htmlAgilityDocument.DocumentNode.SelectNodes("//p"))
{
    if (node.HasClass("ClassName"))
    {
        HtmlAttribute classAttributes = node.Attributes["ClassName"];
        //Do something ...
    }
}

//Select nodes example, get all <p> tag nodes having a specified class name.
string className = "class";
foreach (HtmlNode node in htmlAgilityDocument.DocumentNode.SelectNodes("//p[@class='" + className + "']"))
{
    //Access via class attribute
    HtmlAttribute classAttribute = node.Attributes[className];
    //Do something ...
}

//Get all class names to check for a class
bool containsClass = htmlAgilityDocument.DocumentNode.GetClasses().Contains("ClassName");
if (containsClass == true)
{
    //Do something ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接