A. Hasemeyer
A. Hasemeyer

Reputation: 1734

How to Update HTML Style Attribute

I have a c# .net core 2.2 application that I am trying to parse an HTML page and edit some style attributes on.

I am using HTML Agility Pack

In my HTML I have an Id that has several styles.

<td id="bannerTop" class="alert alert-warning" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 16px; vertical-align: top; color: #fff; font-weight: 500; text-align: center; border-radius: 3px 3px 0 0; background-color: #FF9F00; margin: 0; padding: 20px;" align="center" bgcolor="#FF9F00" valign="top">

I want to call this element "bannerTop" and edit the style background-color

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(selectedTemplate.HtmlTemplateString);

var bannerTop = htmlDoc.GetElementbyId("bannerTop");
bannerTop.Attributes["style"].Value = "background-color: #0000FF";

But that overwrites all style attributes, how can I just edit one of them? Do I need to do a manual parsing of the string that bannerTop.Attributes["style"] returns or is there an easier way that HTML Agility Pack allows to edit a single style?

Upvotes: 1

Views: 1047

Answers (1)

Ryan
Ryan

Reputation: 20106

You need to grab the styles from the attribute and then loop over them to manually change the specific item of styles.

I'd split on the ";" then the ":" to get name/value pairs. Loop over them, lowercase the name and change the value if it matches bgcolor.Otherwise, append original value to newStyles.

var bannerTop = htmlDoc.GetElementbyId("bannerTop");
string oldStyle = bannerTop.Attributes["style"].Value;
string newStyles = "";
foreach (var entries in oldStyle.Split(';'))
{
    var values = entries.Split(':');
    if (values[0].ToLower() == "bgcolor")
    {                                                                   
        values[1] = "#0000FF";
        newStyles += String.Join(':', values) + ";";
    }
    else
    {
        newStyles += entries + ";";
    }

}

bannerTop.Attributes["style"].Value = newStyles;

Upvotes: 1

Related Questions