【问题标题】:Find and add missing style attributes to an html string in C#在 C# 中查找缺失的样式属性并将其添加到 html 字符串
【发布时间】:2017-11-22 18:41:47
【问题描述】:

我陷入了一个棘手的境地,我在 C# 中有这个带有 html 标签的字符串:

字符串 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>";

如您所见,有两个 span 标签没有“font-family: 'Verdana';”。我需要一些可以帮助我将 font-family 添加到这两个跨度标签的东西,所以想要的结果是这样的:

“<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>”

我知道我可以简单地在字符串的开头添加另一个 span 标签,但这是我不想做的事情。 任何帮助将不胜感激。

编辑:我尝试使用 Regex.Replace 方法几个小时。但我就是无法得到正确的输出。

【问题讨论】:

  • HTML 是否保证有效? (平衡的打开/关闭标签、编码等)
  • 是的 .. 这只是我添加的示例 html 供您参考。
  • 所有样式都必须是内联的还是可以使用 CSS 定位元素?此外,目前还不清楚是什么阻止了你做string strHTML ="[the string you want]"

标签: c# html css styles


【解决方案1】:

不使用 Regex 的一种方法是使用 HtmlAgilityPack 库和递归函数:

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

结果:

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

请注意,这不会针对没有样式的 span 标签。如果需要,您可以对其进行修改。

您可以从 NuGet 下载 HtmlAgilityPack 库。

【讨论】:

  • 太棒了..非常感谢胡安。正是我需要的。再次感谢。 :)
猜你喜欢
  • 2021-03-30
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 2011-10-10
相关资源
最近更新 更多