【发布时间】:2020-06-18 14:14:10
【问题描述】:
我有一个输入字符串是 html。它包含图像,我想更改 img 上的 src 属性
到目前为止我的代码如下:
if (htmlStr.Contains("img"))
{
var html = new HtmlDocument();
html.LoadHtml(htmlStr);
var images = html.DocumentNode.SelectNodes("//img");
if (images != null && images.Count > 0)
{
for (int i = 0; i < images.Count; i++)
{
string imageSrc = images[i].Attributes["src"].Value;
string newSrc = "MyNewValue";
images[i].SetAttributeValue("src", newSrc);
}
}
//htmlStr= ???
}
return htmlStr;
我缺少的是如何使用每个图像的 newSrc 值更新我返回的 htmlStr。
【问题讨论】:
-
你试试
html.ToString()? -
@zgood - 没什么好喊的 - 我什至没有想到最直接的解决方案之一就是正确的方法 - 我会试试的
-
@zgood - 将 htmlStr 设置为“HtmlAgilityPack.HtmlDocument” - 我检查了 html.Text 和 html.ParsedText 但我的 img src 都没有更新为 MyNewValue 字符串
标签: c# asp.net .net html-parsing html-agility-pack