Rick
Rick

Reputation: 565

HtmlAgility remove attribute from style parameter of Div node

I am stuck trying to remove a style definition from the style attribute of a DIV element. HTML code:

<div class="el1" style="width:800px; max-width:100%" />
...

<div class="el2" style="width:800px; max-width:100%" />

There may be more than 1 of these elements that I need to apply the manipulation to.

Here is what I have thus far using HtmlAgilityPack.

foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[@style]"))
{
  if (div != null)
  {
    div.Attributes["style"].Value["max-width"].Remove(); //Remove() does not appear to be a function
  }
 }

My thought process was to select any with a style attribute. Look for a max-width definition and remove it.

Any guidance on how this can be achieved?

Upvotes: 3

Views: 2589

Answers (1)

Rick
Rick

Reputation: 565

THanks Marcel for pointing me to the right direction:

Here is the solution that worked for me.

HtmlNodeCollection divs = doc.DocumentNode.SelectNodes("//div[@style]");
            if (divs != null)
            {
                foreach (HtmlNode div in divs)
                {
                    string style = div.Attributes["style"].Value;
                    string pattern = @"max-width(.*?)(;)";
                    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                    string newStyle = regex.Replace(style, String.Empty);
                    div.Attributes["style"].Value = newStyle;
                }
            }

Upvotes: 5

Related Questions