Adding target attribute for all links in html
document using C#, Dotnet ,HtmlAgilityPack
#region "Description"
/*
Description: There are ways that I am going
to explain in this tutorial of adding target element for links in HTML document
1)
Using Normal String Replacement
2)
Using HTMLAgilityPack
*/
#endregion
//1)
Using Normal String Replacement
/// <summary>
/// add Target Elements to links
/// </summary>
/// <param
name="doc">html string without
target element</param>
/// <returns>>html string with target element</returns>
static string AddTargetElementsForLinksUsingReplacement(string HtmlString)
{
try
{
HtmlString =
HtmlString.Replace("<a ", "<a target='_blank' ");
}
catch
(Exception ex)
{
}
return
HtmlString;
}
//2)
Using HTMLAgilityPack
/// <summary>
/// add Target Elements to links
/// </summary>
/// <param
name="htmDoc">HTMLAgiltiyPack
Object of html doc without target element</param>
/// <returns>>HTMLAgiltiyPack Object of html doc with target element</returns>
static HtmlDocument AddTargetElementsForLinks(HtmlDocument htmDoc)
{
string
strPreviousOuterHtml = string.Empty;
try
{
HtmlNodeCollection
nc = htmDoc.DocumentNode.SelectNodes("//a");
if (nc
!= null)
{
foreach
(HtmlNode node in
nc)
{
strPreviousOuterHtml =
node.OuterHtml;
if
(node.Attributes["target"] != null)
node.Attributes["target"].Value = "_blank";
else
node.Attributes.Add("target", "_blank");
htmDoc.DocumentNode.InnerHtml =
htmDoc.DocumentNode.InnerHtml.Replace(strPreviousOuterHtml, node.OuterHtml);
}
}
}
catch (Exception ex)
{
}
return
htmDoc;
}
/// <summary>
/// Adds Target Elemetns to links
/// </summary>
/// <param
name="doc">html string without
target element</param>
/// <returns>>html string with target element</returns>
static string AddTargetElementsForLinks(string HtmlString)
{
string
strPreviousOuterHtml = string.Empty;
HtmlDocument
htmDoc = new HtmlDocument();
try
{
htmDoc.LoadHtml(HtmlString);
HtmlNodeCollection
nc = htmDoc.DocumentNode.SelectNodes("//a");
if
(nc != null)
{
foreach
(HtmlNode node in
nc)
{
strPreviousOuterHtml =
node.OuterHtml;
if (node.Attributes["target"]
!= null)
node.Attributes["target"].Value = "_blank";
else
node.Attributes.Add("target",
"_blank");
htmDoc.DocumentNode.InnerHtml =
htmDoc.DocumentNode.InnerHtml.Replace(strPreviousOuterHtml, node.OuterHtml);
}
}
}
catch
(Exception ex)
{
}
return
htmDoc.DocumentNode.OuterHtml;
}
Today you can also use jQuery Selectors and attributes to add targe link.
ReplyDeleteManish,
Merient Infotech