代码之家  ›  专栏  ›  技术社区  ›  mpen

htmlagilityPack有属性吗?

  •  8
  • mpen  · 技术社区  · 14 年前

    我只想做

    node.Attributes["class"].Value
    

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

    3 回复  |  直到 6 年前
        1
  •  15
  •   Ole Melhus    6 年前

    更新的答案

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

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

        2
  •  3
  •   ATSeaSharp    13 年前

    请尝试此操作:

    String abc = String.Empty;     
          if (tag.Attributes.Contains(@"type"))
          {
              abc = tag.Attributes[@"type"].Value;
          }
    
        3
  •  0
  •   Syed Asim Shah    9 年前

    此代码可用于获取两个脚本标记之间的所有文本。

    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;
        }
    
    推荐文章