日期:2014-05-17 浏览次数:20764 次
string source = @"<img src="""" alt=""""> <img src="""" > <img src="""" title=""""> <img src="""" id=""""> <img src="""" title="""" alt=""""> ";
foreach (Match m in Regex.Matches(source, @"(?is)<img(?![^<>]*?alt[^<>]*?>)[^>]*?>"))
{
Console.WriteLine(Regex.Replace(m.Value, @"(?<=<img\s*).*?(?=/?>)", @"$0alt=""XXX"""));
}
string yourhtml = @"<img src='xxx.jpg'>
<img src='xxx.jpg' alt='yyy'> ";
Console.WriteLine(yourhtml);
yourhtml = Regex.Replace(yourhtml, "(?i)(?<=<img\\b)[^>]*?(?=>)", m => m.Value.Contains("alt=") ? m.Value : m.Value+ " alt='XXX'");
Console.WriteLine(yourhtml);
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml("<img src='1.jpg'/><img src='2.jpg' alt='value'/><img src='3.jpg' /><img src='alt.jpg' title='alt=value'/><img src='5.jpg' alt=''/>");
htmlDoc.DocumentNode.SelectNodes("//img[not(@alt)]").ToList().ForEach(x => x.SetAttributeValue("alt", "xxxxx"));
Response.Write(Server.HtmlEncode(htmlDoc.DocumentNode.InnerHtml));