【问题标题】:Set img src with Html Agility Pack使用 Html Agility Pack 设置 img src
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • @grud - 我刚刚自己编写了 StringWriter 选项,并准备将其发布为我的答案 - 认为我会接受它,我已将您的答案标记为已接受
猜你喜欢
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
相关资源
最近更新 更多