使用Html敏捷包设置img src



我有一个输入字符串,它是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。

据我所知,您有两个选项:

// Will give you a raw string.
// Not ideal if you are planning to
// send this over the network, or save as a file.
var updatedStr = html.DocumentNode.OuterHtml;
// Will let you write to any stream.
// Here, I'm just writing to a string builder as an example.
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
html.Save(writer);
}
// These two methods generate the same result, though.
Debug.Assert(string.Equals(updatedStr, sb.ToString()));

最新更新