Find and add missing style attributes to an html s

2019-09-21 16:51发布

问题:

I am stuck in a tricky situation, I have this string in C# with html tags :

string strHTML = "<span style="font-size: 10px;">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px;">Please help</span><span>me add style attributes to span tags.Thank You</span>";

As you can see, there are two span tags without "font-family: 'Verdana';". I need something that can help me add font-family to those two span tags so the desired result would be something like this:

"<span style="font-size: 10px;font-family: 'Verdana';">Hi This is just an example of html text.</span><span style="font-family: 'Verdana'; font-size: 10px;">Please help<span style="font-family: 'Verdana';">me add style attributes to span tags.Thank You</span>"

I know that I can simply add another span tag at the beginning of the string but that is something I don't want to do. Any help would be much appreciated.

Edits: I tried using Regex.Replace method for hours. But I just could not get the correct output.

回答1:

One way of doing it without Regex would be to use the HtmlAgilityPack library and a recursive function:

public void SetFonts()
{
    string strHtml = "<span style=\"font-size: 10px; \">Hi This is just a section of html text.</span><span style=\"font-family: 'Verdana'; font-size: 10px; \">Please help</span><span>me add style attributes to span tags.Thank You</span>";
    HtmlDocument document = new HtmlDocument();
    document.LoadHtml(strHtml);
    SetFonts(document.DocumentNode);
    document.Save(Console.Out);
}


public void SetFonts(HtmlNode node)
{
    foreach (var item in node.Elements("span"))
    {
        var style = item.GetAttributeValue("style", null);
        if (style != null)
        {
            if (!style.Contains("font-family"))
            {
                var newValue = style + "font-family: 'Verdana';";
                item.SetAttributeValue("style", newValue);
            }
        }
        SetFonts(item);
    }            
}

The result:

<span style="font-size: 10px; font-family: 'Verdana';">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px; ">Please help</span><span>me add style attributes to span tags.Thank You</span>

Note this won't target span tags with no style at all. You can modify it to do so if you need.

You can download the HtmlAgilityPack library from NuGet.



标签: c# html css styles