2013-08-06 101 views
1

我有一個完整的HTML字符串。它看起來像這樣:在完整的html字符串中清理img標籤

<html> 
    <head> 
    </head> 
    <body> 
    This is a test 
    <img width=403 height="302" id="someid1" src="http://mysite.com/images1"> 
    <img width="456" height=300 src="http://mysite.com/images2" id="someid2"> 
    </body> 
</head> 

我想要做的就是清理源代碼。我只想移除img標籤中的所有寬度和高度。我想保留ID和SRC屬性。

+0

有什麼不對編輯的文本? –

回答

3

你不需要這裏的正則表達式。使用像HtmlAgilityPack HTML解析器會更好..

var doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(html); 

foreach (var img in doc.DocumentNode.Descendants("img")) 
{ 
    img.Attributes.Remove("width"); 
    img.Attributes.Remove("height"); 
} 

var newhtml = doc.DocumentNode.OuterHtml;