Using htmlagility pack to replace src values

c# html html-agility-pack html-manipulation src

Question

A CMS system is what I'm utilizing for my website. My content creators uploaded some large photographs to the system, and then they resized them in the CMS to make them fit the page or article. Even if the donor downsized the picture, when a user accesses that website, they download the whole image. All I have to do is put the width and height parameters after the picture name in the src of an image resizer plugin that I have discovered. According to a search, I should be utilizing the HTML Agility Pack to do this, but could someone please assist me complete my code? Finding the image tags inside the content is something I've worked out, but I'm not sure how to add the url with the width and height.

Aged Tag

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

To this, observe how the src value has changed.

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

So far, here is my code. All I need is some assistance in the if statement to specify that the src property should be appended if the image tag includes either a width or a height.

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
    }
}
1
6
7/1/2015 1:51:36 PM

Accepted Answer

Do this:

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));
    }
}
12
7/9/2012 9:33:57 PM

Popular Answer

You may skip the if if you use an XPath that only chooses nodes with src and width or height:

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

But be careful—according to my memory of HTMLAgilityPack, SelectNodes returns null if nothing matches.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow