使用 Html Agility Pack 设置 img src

Set img src with Html Agility Pack

我有一个输入字符串 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;

我缺少的是如何更新 htmlStr 我返回每个图像的 newSrc 值。

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

// 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()));