You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ASP.NET C#实现HTML中img标签冗余属性移除功能?

实现方案

推荐方案:使用HtmlAgilityPack解析处理(无破坏其他HTML结构风险)

HtmlAgilityPack是.NET生态下成熟的HTML解析库,能完美保留原HTML结构,仅修改目标img标签属性,不会出现正则方案容易误改其他内容的问题。

第一步:安装依赖

通过NuGet安装HtmlAgilityPack包即可。

第二步:函数实现

注意:原骨架中的参数名html-string不符合C#变量命名规范,实现中调整为合法命名htmlString

using HtmlAgilityPack;
using System.Linq;

public static string FixImageAttributes(string htmlString)
{
    // 允许保留的属性白名单
    var allowedAttributes = new[] { "src", "align", "alt", "title" };
    
    HtmlDocument doc = new HtmlDocument();
    // 配置保留原HTML的格式、大小写等设置
    doc.OptionOutputOriginalCase = true;
    doc.OptionWriteEmptyNodes = true;
    doc.LoadHtml(htmlString);
    
    // 查找所有img标签
    var imgNodes = doc.DocumentNode.Descendants("img").ToList();
    foreach (var img in imgNodes)
    {
        // 遍历img的所有属性,移除不在白名单里的
        var attributesToRemove = img.Attributes
            .Where(attr => !allowedAttributes.Contains(attr.Name.ToLower()))
            .ToList();
        foreach (var attr in attributesToRemove)
        {
            img.Attributes.Remove(attr);
        }
    }
    
    // 输出处理后的HTML
    return doc.DocumentNode.OuterHtml;
}

可选方案:正则实现(不推荐,仅适用于结构规范的HTML场景)

如果不想引入第三方依赖,且确定输入HTML结构非常规范,可以用正则替换实现,注意对复杂不规范HTML可能有匹配错误风险:

using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

public static string FixImageAttributes(string htmlString)
{
    var allowedAttributes = new[] { "src", "align", "alt", "title" };
    return Regex.Replace(htmlString, @"<img\s+[^>]*>", match =>
    {
        string imgTag = match.Value;
        // 匹配所有属性
        var attributeMatches = Regex.Matches(imgTag, @"(?<name>\w+)\s*=\s*([""'])(?<value>.*?)\2");
        List<string> keepAttrs = new List<string>();
        foreach (Match attrMatch in attributeMatches)
        {
            string attrName = attrMatch.Groups["name"].Value.ToLower();
            if (allowedAttributes.Contains(attrName))
            {
                keepAttrs.Add($"{attrMatch.Groups["name"].Value}={attrMatch.Groups[2].Value}{attrMatch.Groups["value"].Value}{attrMatch.Groups[2].Value}");
            }
        }
        return $"<img {string.Join(" ", keepAttrs)}>";
    }, RegexOptions.IgnoreCase);
}

内容的提问来源于stack exchange,提问作者Øyvind Isaksen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:00:01