使用htmlagility包替换src值

JK3*_*K36 6 html c# src html-manipulation html-agility-pack

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

旧标签

<img src="/IMG_3556E__sq2.jpg?n=9418" id="/IMG_3556E__sq2.jpg?n=9418" width="83px" height="83px" />
Run Code Online (Sandbox Code Playgroud)

对此 - 请注意src值已更改

<img src="/IMG_3556E__sq2.jpg?width=83&amp;height=83" id="/IMG_3556E__sq2.jpg?n=9418" width="83px" height="83px" />
Run Code Online (Sandbox Code Playgroud)

到目前为止这是我的代码.我需要的只是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
    }
}
Run Code Online (Sandbox Code Playgroud)

Len*_*rri 11

试试这个:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)