遍历html字符串以查找所有img标签并替换src属性值

D B

我有一个HTML代码作为字符串。我需要找到该字符串中的所有img标签,读取每个src属性的值,并将其传递给函数,该函数将返回一个完整的img标签,该标签需要替换已读取的img标签。

它需要遍历整个字符串,并对所有img标签执行相同的逻辑。

例如,假设我的html字符串如下所示:

string htmlBody= "<p>Hi everyone</p><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA..." <p>I am here </p> <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABAC..." />"

我有以下代码,该代码找到第一个img标签,并采用src值(它是base64字符串)并将其转换为位数组以创建流,然后可以创建一个新的src值,该值链接到该流。

  //Remove from all src attributes "data:image/png;base64"      
  string res = Regex.Replace(htmlBody, "data:image\\/\\w+\\;base64\\,", "");
  //Match the img tag and get the base64  string value
  string matchString = Regex.Match(res, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
  var imageData = Convert.FromBase64String(matchString);
  var contentId = Guid.NewGuid().ToString();
  LinkedResource inline = new LinkedResource(new MemoryStream(imageData), "image/jpeg");
  inline.ContentId = contentId;
  inline.TransferEncoding = TransferEncoding.Base64;
  //Replace all img tags with the new img tag 
  htmlBody = Regex.Replace(htmlBody, "<img.+?src=[\"'](.+?)[\"'].*?>", @"<img src='cid:" + inline.ContentId + @"'/>");

如您所见,finnaly我已经替换了新的img标签:

   <img src='cid:" + inline.ContentId + @"'/>

但是代码会将所有img标签替换为相同的内容。我需要能够获取img标签,执行逻辑,替换它,然后继续下一个img标签。

希望你能给我一个主意,我该怎么做。提前致谢。

齐汉·尤根

如果我正确了解您的需求,则可以为此目的使用HtmlAgilityPack。使用正则表达式可能会导致不良行为。您可以尝试以下代码吗?

public static string DoIt()
{
        string htmlString = "";
        using (WebClient client = new WebClient())
            htmlString = client.DownloadString("http://dean.edwards.name/my/base64-ie.html"); //This is an example source for base64 img src, you can change this directly to your source.

        HtmlDocument document = new HtmlDocument();
        document.LoadHtml(htmlString);
        document.DocumentNode.Descendants("img")
                            .Where(e =>
                            {
                                string src = e.GetAttributeValue("src", null) ?? "";
                                return !string.IsNullOrEmpty(src) && src.StartsWith("data:image");
                            })
                            .ToList()
                            .ForEach(x =>
                            {
                                string currentSrcValue = x.GetAttributeValue("src", null);
                                currentSrcValue = currentSrcValue.Split(',')[1];//Base64 part of string
                                byte[] imageData = Convert.FromBase64String(currentSrcValue);
                                string contentId = Guid.NewGuid().ToString();
                                LinkedResource inline = new LinkedResource(new MemoryStream(imageData), "image/jpeg");
                                inline.ContentId = contentId;
                                inline.TransferEncoding = TransferEncoding.Base64;

                                x.SetAttributeValue("src", "cid:" + inline.ContentId);
                            });


        string result = document.DocumentNode.OuterHtml;
}

您可以从https://www.nuget.org/packages/HtmlAgilityPack检索HtmlAgilityPack

希望这可以帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在golang中用空字符串替换所有html标签

从php字符串中删除所有html标签

通过src值查找img标签,并在img标签中添加新属性

Python,从字符串中删除所有html标签

查找并替换范围中所有出现的字符串

PHP替换image src并从包含不同html标签的字符串中在image标签中添加新属性

如何遍历所有字符串属性并使用System.Reflection更改其值

如何使用查找和替换用vscode中的kebab字符串替换所有驼峰式字符串

遍历某个字符串的所有出现,并用C#中的不同值替换每个字符串?

如何从Android中的字符串替换<img>标签的src属性

Netbeans查找并替换所有字符串

jQuery替换RegEx所有字符串值

替换HTML字符串中的所有<a>标签

Unix命令来查找和替换字符串,并列出替换了字符串的所有文件

在字符串中查找src的值

查找和替换字符串之前的所有内容

如何从字符串中剥离所有HTML标签?

PHP查找并替换字符串中的html属性

查找包含 HTML 的字符串中的所有出现

如何遍历逗号分隔的字符串属性,拆分字符串并从所有不同的值创建 ICollection

Python:搜索和替换 HTML 字符串中的所有 img 标签

如何使用 jquery/javascript 在图像标签 <img src=""> 的 src 属性中传递字符串?

替换 HTML 字符串中 HTML 标签属性的引号

使用 EPPLUS 查找和替换所有字符串

通过php查找和替换字符串中的Img标签?

替换所有字符串大于 X 的观测值

使用 Puppeteer 检索网页上所有 HTML IMG 标签的 SRC 属性

如何删除所有 html 标签,包括“ ” 从字符串?

使用 RegEx 替换 html 字符串中的所有图像 src 属性