Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add <link> or <meta> tags to <head> with HtmlAgilityPack?

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

like image 861
DaveDev Avatar asked Dec 09 '22 15:12

DaveDev


1 Answers

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>
like image 184
Simon Mourier Avatar answered Dec 31 '22 16:12

Simon Mourier