HtmlAgility remove attribute from style parameter of Div node

c# html-agility-pack

Question

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?

Accepted Answer

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why