简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM