【问题标题】:Get colored texts within HTML code在 HTML 代码中获取彩色文本
【发布时间】:2012-04-18 06:22:14
【问题描述】:

我有一个 Html 代码,我想将它转换为纯文本,但只保留彩色文本标签。 例如: 当我有以下 Html:

<body>

This is a <b>sample</b> html text.
<p align="center" style="color:#ff9999">this is only a sample<p>
....
and some other tags...
</body>
</html>

我想要输出:

this is a sample html text.
<#ff9999>this is only a sample<>
....
and some other tags...

【问题讨论】:

  • 你写的代码是什么
  • thanx,未指定代码。带有颜色名称标签的纯文本。
  • 但是你需要写一些代码来解析代码,对吧?
  • @Ali.M - Satya 的意思是你用什么来尝试实现这一目标? jQuery? php?正则表达式?
  • 另外,您想将&lt;p&gt; 替换为&lt;&gt;,但&lt;b&gt; 什么都不替换?

标签: c# html html-parsing


【解决方案1】:

我会使用解析器来解析 HTML,如 HtmlAgilityPack,并使用正则表达式在属性中查找 color 值。

首先,使用xpath找到所有包含style属性和color的节点:

var doc = new HtmlDocument();
doc.LoadHtml(html);
var nodes = doc.DocumentNode
    .SelectNodes("//*[contains(@style, 'color')]")
    .ToArray();

然后是匹配颜色值的最简单的正则表达式:(?&lt;=color:\s*)#?\w+

var colorRegex = new Regex(@"(?<=color:\s*)#?\w+", RegexOptions.IgnoreCase);

然后遍历这些节点,如果有正则匹配,用html编码的标签替换节点的内部html(稍后你会明白为什么):

foreach (var node in nodes)
{
    var style = node.Attributes["style"].Value;
    if (colorRegex.IsMatch(style))
    {
        var color = colorRegex.Match(style).Value;
        node.InnerHtml =
            HttpUtility.HtmlEncode("<" + color + ">") +
            node.InnerHtml +
            HttpUtility.HtmlEncode("</" + color + ">");
    }
}

最后得到文档的内部文本并对其进行html解码(这是因为内部文本剥离了所有标签):

var txt = HttpUtility.HtmlDecode(doc.DocumentNode.InnerText);

这应该返回如下内容:

This is a sample html text.
<#ff9999>this is only a sample</#ff9999>
....
and some other tags...

当然,您可以根据自己的需要对其进行改进。

【讨论】:

    【解决方案2】:

    可以使用正则表达式来做到这一点,但是...You should not parse (X)HTML with regex.

    我用来解决问题的第一个正则表达式是:

    <p(\w|\s|[="])+color:(#([0-9a-f]{6}|[0-9a-f]{3}))">(\w|\s)+</p>
    

    第 5 组将是十六进制(3 或 6 个十六进制)颜色,第 6 组将是标记内的文本。

    显然,这不是最好的解决方案,因为我不是正则表达式大师,显然它需要一些测试和可能的概括......但它仍然是一个很好的起点。

    【讨论】:

    • 谢谢,但它不起作用。我正在更多地使用正则表达式来找出解决方案。
    猜你喜欢
    • 2018-01-05
    • 2013-08-26
    • 2016-04-10
    • 1970-01-01
    • 2011-07-22
    • 2015-07-02
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多