2012-07-09 70 views
4

我正在为网站使用CMS系统。我的内容贡献者在系统中放置了一些非常大的图像,然后继续在cms中调整它们的大小,以使它们适合页面或文章。当web用户访问该页面时,即使贡献者调整了图像大小,他们也会下载完整图像。我找到了一个图像大小写插件,我所需要做的就是在src中的图像名称后面添加宽度和高度参数。做一个搜索,它看起来像我应该使用HTML敏捷包来实现这一目标,但有人可以帮助我完成我的代码。我找到了如何在内容中找到img标签,但我不知道如何在宽度和高度上添加src。使用htmlagility包来替换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 
    } 
} 

回答

7

试试这个:

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)); 
    } 
} 
+0

感谢Leniel,这读起来好像它会起作用。我无法弄清楚的一件事是如何对Content.html进行更改。我知道你setattribute,但可以设置它在内存中,因为当我response.write(content.html)它仍然显示原始的HTML – JK36 2012-07-09 22:04:22

+2

我认为你必须调用'htmlDoc.Save(...)'... – 2012-07-09 22:21:06

+0

再次感谢指针。我认为保存()是如果你想保存一个物理副本的变化。不知道如何在内存中为CMS程序包执行此操作。会做一些阅读,但应该是直接传递给另一个html变量并显示的情况。 – JK36 2012-07-09 22:31:31

2

如果您使用的是只选择与src和宽度或高度节点的XPath,你可以省略,如果:

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

但要注意:如果没有匹配,SelectNodes将返回null,就我记得的HtmlAgilityPack而言。