HasAttribute in HtmlAgilityPack?

c# html-agility-pack

Question

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
8
11/3/2010 6:12:35 PM

Accepted Answer

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.

16
2/19/2019 9:56:43 AM

Popular Answer

Please try this:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow