繁体   English   中英

如何对HTML字符串使用String.Replace方法

[英]How to use String.Replace method for html string

我在字符串变量中有html代码。 因为我有多个图像标签,所以我想用新的src替换图像标签的src。

我正在使用此代码:

    foreach (MessagePart attchment in unseenMessage.FindAllAttachments())
    {
         attchments =  Guid.NewGuid().ToString() + attchment.FileName;
         string src="cid:"+ attchment.ContentId;
         string newsrc = "/Attachment/" + attchments;
         emailbody.Replace(src, newsrc);
         string filepath = "D:\\AceoCRM\\Aceo.Web\\Attachment\\" + attchments;
         using (FileStream fs = new FileStream(filepath, FileMode.CreateNew))
         {

              fs.Write(attchment.Body, 0, attchment.Body.Length);
              fs.Close();
         }
         listOfAttachments.Add(attchments);
    }

您可以使用HtmlAgilityPack解析和替换内部html和图像源中的标签。

编辑:示例:替换src

var documnet = new HtmlDocument();
documnet.LoadHtml("HtmlString");
foreach (var href in documnet.DocumentNode.Descendants("img").Where(href => !href.OuterHtml.Trim().Contains("http")))
{
     try
     {
          //here image src URL being changed...
          href.Attributes["src"].Value = href.Attributes["src"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["src"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["src"].Value.TrimFromStart("//"));
          href.Attributes["srcset"].Value = href.Attributes["srcset"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["srcset"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["srcset"].Value.TrimFromStart("//"));
     }
     catch (NullReferenceException ex)
     {
         Log(ex);
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM