【问题标题】:Using htmlagility pack to replace src values使用 htmlagility pack 替换 src 值
【发布时间】:2012-07-09 07:37:28
【问题描述】:

我正在为网站使用 CMS 系统。我的内容贡献者在系统中放置了一些非常大的图像,然后继续在 cms 中调整它们的大小,以便它们适合页面或文章。当网络用户点击该页面时,他们会下载完整的图像,即使贡献者已经调整了图像的大小。我找到了一个图像缩放插件,我需要做的就是在 src.xml 中的图像名称后面添加宽度和高度参数。进行搜索看起来我应该使用 html 敏捷包来实现这一点,但有人可以帮我完成我的代码。我想出了如何在内容中找到 img 标签,但我不知道如何在 src 中附加宽度和高度。

旧标签

<img src="/IMG_3556E__sq2.jpg?n=9418" id="/IMG_3556E__sq2.jpg?n=9418" width="83px" height="83px" />

至此 - 注意 src 值已更改

<img src="/IMG_3556E__sq2.jpg?width=83&amp;height=83" id="/IMG_3556E__sq2.jpg?n=9418" width="83px" height="83px" />

到目前为止,这是我的代码。我需要的只是 if 语句中的帮助,说明 img 标签是否包含宽度或高度,将它们附加到 src 属性。

ContentManager contentManager = new ContentManager();
ContentData Content = contentManager.GetItem(id);

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Content.Html);

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//img/@src"))
{
    if (//img has a width or height, it means image has been resized) {
        //append that nodes src within the content.html with the ?width=x&height=x
    }
}

【问题讨论】:

    标签: c# html html-agility-pack src html-manipulation


    【解决方案1】:

    试试这个:

    static void Main(string[] args)
    {
        var htmlDoc = new HtmlDocument();
        htmlDoc.Load(@"E:\Libs\HtmlAgilityPack.1.4.0\htmldoc.html");
    
        foreach(HtmlNode node in htmlDoc.DocumentNode
                                       .SelectNodes("//img[@src and (@width or @height)]"))
        {
            var src = node.Attributes["src"].Value.Split('?');
    
            var width = node.Attributes["width"].Value.Replace("px", "");
    
            var height = node.Attributes["height"].Value.Replace("px", "");
    
            node.SetAttributeValue("src",
                                    src[0] +
                                    string.Format("?width={0}&height{1}", width, height));
        }
    }
    

    【讨论】:

    • 感谢 Leniel,这看起来好像可以工作。我不知道的一件事是如何更改 Content.html。我知道你 setattribute,但大概将它设置在内存中,因为当我 response.write(content.html) 它仍然显示原始 html
    • 再次感谢您的指点。我认为 Save() 是如果您想保存更改后的物理副本。不确定如何在内存中动态执行 CMS 包。会做一些阅读,但应该是直接传递到另一个 html 变量并显示它的情况。
    • 好吧,在我在本地运行的示例中,如果我要执行response.write(htmlDoc),它将编写文档的内存修改版本。不知道你是什么情况。
    • 谢谢 - 我设法通过输入 Content.Html = Content.Html.Replace(src[0], src[0] + string.Format("?width={0 }&height{1}", 宽度, 高度));
    【解决方案2】:

    如果您使用的 XPath 仅选择具有 src 和宽度或高度的节点,则可以省略 if:

    foreach (HtmlNode node in doc.DocumentNode
        .SelectNodes("//img[@src and (@width or @height)]"))
    {
        node.SetAttributeValue("src",  ...);
    }
    

    但要小心:如果没有匹配项,SelectNodes 返回 null - 据我记得 HtmlAgilityPack。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      相关资源
      最近更新 更多