gpt4 book ai didi

c# - HTML 条函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:23:57 26 4
gpt4 key购买 nike

有一个棘手的问题。

我有一个 HTML 需要去除一些标签、属性和属性

基本上可以考虑三种不同的方法:

  • 字符串操作:遍历 HTML 字符串并通过字符串操作“手动”去除它
  • 正则表达式:Parsing HTML with RegEx is evil.剥离 HTML 也是邪恶的吗?
  • 使用库对其进行剥离(例如 HTML Agility Pack)

我希望我有列表:

  • 接受标签(例如 SPAN、DIV、OL、LI)
  • acceptedAttributes(例如 STYLE、SRC)
  • 接受的属性(例如文本对齐、字体粗细、颜色、背景颜色)

我可以将其传递给剥离 HTML 的函数。

示例输入:

<BODY STYLE="font-family:Tahoma;font-size:11;"> <DIV STYLE="margin:0 0 0 0;text-align:Left;font-family:Tahoma;font-size:16;"> <SPAN STYLE="font-weight:bold;color:#000000;background-color:#FF0000;font-family:tahoma;font-size:11;">Hello</SPAN></BODY>

示例输出(带有上面的参数列表):

<DIV STYLE="text-align:Left;"> <SPAN STYLE="font-weight:bold;color:#000000;background-color:#FF0000;">Hello</SPAN>
  1. 整个标签主体被剥离(不接受标签)
  2. 属性 margin、font-family 和 font-size 从 DIV-Tag 中剥离
  3. 属性 font-family 和 font-size 从 SPAN-Tag 中剥离。

我尝试了什么?

Regex 乍一看似乎是最好的方法。但我无法让它正常工作。我看过的关于 Stackoverflow 的文章:

...还有更多。

我尝试了以下正则表达式:

Dim AcceptableTags As String = "font|span|html|i|b|u|sup|sub|ol|ul|li|br|h2|h3|h4|h5|span|div|p|a|img|blockquote"
Dim WhiteListPattern As String = "</?(?(?=" & AcceptableTags & _
")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>"
Dim Html as String = Regex.Replace(b.HTML, WhiteListPattern, "", RegexOptions.Compiled)

但是,这只是删除标签,没有属性或属性!

我绝对不是在找一个包揽所有工作的人。而是为某人指明了正确的方向。

我对 C# 或 VB.NET 作为答案很满意。

最佳答案

一定要用库! (参见 this)

使用 HTMLAgilityPack,您几乎可以做任何您想做的事情:

  1. 删除不需要的标签:

    string[] allowedTags = {"SPAN", "DIV", "OL", "LI"};
    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//node()"))
    {
    if (!allowedTags.Contains(node.Name.ToUpper()))
    {
    HtmlNode parent = node.ParentNode;
    parent.RemoveChild(node,true);
    }
    }
  2. 删除不需要的属性并删除属性

    string[] allowedAttributes = { "STYLE", "SRC" };

    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//node()"))
    {
    List<HtmlAttribute> attributesToRemove = new List<HtmlAttribute>();
    foreach (HtmlAttribute att in node.Attributes)
    {
    if (!allowedAttributes.Contains(att.Name.ToUpper())) attributesToRemove.Add(att);
    else
    {
    string newAttrib = string.Empty;
    //do string manipulation based on your checking accepted properties
    //one way would be to split the attribute.Value by a semicolon and do a
    //String.Contains() on each one, not appending those that don't match. Maybe
    //use a StringBuilder instead too

    att.Value = newAttrib;
    }
    }
    foreach (HtmlAttribute attribute in attributesToRemove)
    {
    node.Attributes.Remove(attribute);
    }

    }

关于c# - HTML 条函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26991134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com