Find and add missing style attributes to an html string in C#

大兔子大兔子 提交于 2019-12-13 09:05:07

问题


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.



来源:https://stackoverflow.com/questions/47441815/find-and-add-missing-style-attributes-to-an-html-string-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!