【问题标题】:Regular expression to replace image tag src attribute value正则表达式替换图片标签src属性值
【发布时间】:2016-01-24 12:02:00
【问题描述】:

我有一个string,其中包含文档的 html 代码。

里面可以有multiple image tags

我想要做的是将 img 标签的 src 属性值(即 url)传递给 C# 函数,并将该值替换为函数返回值。

我该怎么做?

【问题讨论】:

标签: c# asp.net regex


【解决方案1】:

正则表达式不适合解析 HTML 文件。HTML 不严格,格式也不规则。(例如:在非严格的 html 中,它的 OK 有一个没有结束标签的标签)

使用htmlagilitypack

你可以使用htmlagilitypack来做这样的事情

HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);

foreach(var item in doc.DocumentNode.SelectNodes("//img[@src]"))//select only those img that have a src attribute..ahh not required to do [@src] i guess
{
 item.Attributes["src"].Value=yourFunction(item.Attributes["src"].Value);
}
doc.Save("yourFile");//dont forget to save

【讨论】:

  • 我在字符串中传递 HTML,我想用替换值返回该字符串。我不想将其保存在文件中。我该怎么做?
  • @DevendraGohil 使用doc.DocumentNode.OuterHtml 获取完整的html
猜你喜欢
  • 2023-03-09
  • 2012-04-10
  • 2012-05-26
  • 2015-07-06
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
相关资源
最近更新 更多