HtmlAgilityPack HasAttribute?

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

All I want to do is

node.Attributes["class"].Value 

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?

回答1:

Try this:

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

Or you might be able to add this

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

And then use

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

I havent tested that one, but it should work.



回答2:

Please try this:

String abc = String.Empty;            if (tag.Attributes.Contains(@"type"))       {           abc = tag.Attributes[@"type"].Value;       } 


回答3:

This Code Can Be Used to get all text between two script tags.

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;     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!