Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlAgilityPack HasAttribute?

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?

like image 350
mpen Avatar asked Nov 03 '10 18:11

mpen


2 Answers

Updated answer

Use node.Attributes["class"]?.Value to return null if the attribute is missing. This will be the same as the ValueOrDefault() below.

Original answer

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.

like image 51
Ole Melhus Avatar answered Sep 20 '22 13:09

Ole Melhus


Please try this:

String abc = String.Empty;     
      if (tag.Attributes.Contains(@"type"))
      {
          abc = tag.Attributes[@"type"].Value;
      }
like image 41
ATSeaSharp Avatar answered Sep 20 '22 13:09

ATSeaSharp