Recentemente, preciso exibir uma prévia de um texto HTML.
Basicamente, um usuário cadastra uma nova entrada no blog (por exemplo) e a ideia é exibir uma prévia deste post.
public static string GetFirstTag(this string htmlText)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlText);
var imgNode = htmlDoc.DocumentNode.SelectSingleNode("//img[@src]");
return imgNode != null
? imgNode.Attributes["src"].Value
: "";
}
public static string GetSummaryHTML(this string htmlText, int maxWords, int maxParagrafos = int.MaxValue, bool addReticencias = false)
{
string summaryHtml = string.Empty;
int wordCount = 0;
int paragrafoCount = 0;
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlText);
foreach (var element in htmlDoc.DocumentNode.ChildNodes)
{
string elementText = element.InnerText;
summaryHtml += "<p>";
paragrafoCount++;
foreach (var word in elementText.Split(new[] {' '}))
{
summaryHtml += word + " ";
wordCount++;
if (wordCount >= maxWords)
return summaryHtml + (addReticencias ? ".." : "") + "</p>";
}
summaryHtml += "</p>";
if (paragrafoCount >= maxParagrafos)
return summaryHtml;
}
return summaryHtml + "</p>";
}
public static string GetSummaryText(this string htmlText, int maxWords, bool addReticencias = false)
{
string summaryHtml = string.Empty;
int wordCount = 0;
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlText);
foreach (var element in htmlDoc.DocumentNode.ChildNodes)
{
string elementText = element.InnerText;
foreach (var word in elementText.Split(new[] {' '}))
{
summaryHtml += word + " ";
wordCount++;
if (wordCount > maxWords)
return summaryHtml + (addReticencias ? ".." : "");
}
}
return summaryHtml;
}
Para isso utilizei o HTML Agility Pack http://htmlagilitypack.codeplex.com/