How to add or tags to with HtmlAgilityPack?

asp.net-mvc c# dom html html-agility-pack

Question

The link to download documentation from http://htmlagilitypack.codeplex.com is returning an error and I can't figure this out by trying the code.

I'm trying to insert various tags into the <head> section of a HtmlDocument that I've loaded from a HTML string. The original issue I'm having is described here.

Can somebody give me an idea of how to achieve this? Thanks

Popular Answer

Maybe a bit late :-) Suppose I have this test.htm Html file:

<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    Hello World
</body>
</html>

Here is how to add a LINK element underneath the HEAD element. You will not the semantics is very close to the System.Xml one, on purpose:

HtmlDocument doc = new HtmlDocument();
doc.Load("test.htm");

HtmlNode head = doc.DocumentNode.SelectSingleNode("/html/head");

HtmlNode link = doc.CreateElement("link");
head.AppendChild(link);
link.SetAttributeValue("rel", "shortcut icon");
link.SetAttributeValue("href", "http://www.mysite.com/favicon.ico");

The result will be:

<html>
<head>
    <title>Hello World!</title>
<link rel="shortcut icon" href="http://www.mysite.com/favicon.ico"></head>
<body>
    Hello World
</body>
</html>


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why