C# +HTMLAgilityPack: retrive background-url value

c# css html-agility-pack

Question

I'm going to extract background of some HTML files and replace them with new values.
In order to control if BODY tag got background defined in its style as css i used below code:

foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))
{
  if (bodyNode.Attributes.Contains("style") && bodyNode.Attributes["style"].Value.Replace(" ","").Contains("background-image:url"))
  {
    //code to replace background-url
  }

}

my problem is how to retrive background-url value from such tag from style properties:

<body style="background-image: url('test/bg.jpg')" >

and replace it with new value like below:

<body style="background-image: url('new value')" >

Accepted Answer

Try code below. Extract background-image url (string between brackets) with regex and replace it with new image. Now remove style attribute and add new (style with replaced image).

This will work with all properties values and formats.

           foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))
            {
                string newImg = "new-value.png";
                if (bodyNode.Attributes.Contains("style") && bodyNode.Attributes["style"].Value.Contains("background-image:url"))
                {                     
                    string style = bodyNode.Attributes["style"].Value;
                    string oldImg = Regex.Match(style, @"(?<=\().+?(?=\))").Value;
                    string oldStyle = bodyNode.Attributes["style"].Value;
                    string newStyle = oldStyle.Replace(oldImg, newImg);

                    bodyNode.Attributes.Remove("style");
                    bodyNode.Attributes.Add("style", newStyle);
                }

            }

Popular Answer

you can remove the old style and add the new style for example:

bodyNode.Attributes.Remove("style");
bodyNode.Attributes.Add("style", "width:95%;background-image: url('test/bg1.jpg');font-size:xx-large;text-align:center");



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