How can I attach an element to the top of the Head element in HTML Agility Pack?

.net c# html-agility-pack


I'm trying to use HTML Agility Pack to append a script element into the top of the HEAD section of my html. The examples I have seen so far just use the AppendChild(element) method to accomplish this. I need the script that I am appending to the head section to come before some other scripts. How can I specify this?

Here's what I'm trying:

HtmlDocument htmlDocument = new HtmlDocument();
HtmlNode head = htmlDocument.DocumentNode.SelectSingleNode("/html/head");
HtmlNode stateScript = htmlDocument.CreateElement("script");
stateScript.SetAttributeValue("id", "applicationState");
stateScript.InnerHtml = "'{\"uid\":\"testUser\"}'";

I would like a script tag to be added toward the top of HEAD rather than appended at the end.

9/17/2014 4:59:41 PM

Popular Answer

Realizing that this is an old question, there is also the possibility of prepending child elements that might not have existed then.

// Load content as new Html document
HtmlDocument html = new HtmlDocument();

// Wrapper acts as a root element
string newContent = "<div>" + someHtml + "</div>";

// Create new node from newcontent
HtmlNode newNode = HtmlNode.CreateNode(newContent);

// Get body node
HtmlNode body = html.DocumentNode.SelectSingleNode("//body");

// Add new node as first child of body

// Get contents with new node
string contents = html.DocumentNode.InnerHtml;
7/19/2012 6:24:20 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow