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

.net c# html-agility-pack


I'm attempting to add a script element at the top of the HEAD section of my HTML document using HTML Agility Pack. The examples I've seen so far only make use ofAppendChild(element) a way to make this happen. The script I am adding to the head section must appear before several other scripts, per my need. How can I make this clear?

This is what I'm attempting:

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

Instead of being put at the end of HEAD, a script tag should go towards the top.

9/17/2014 4:59:41 PM

Popular Answer

Considering that this is an ancient question, it's also possible that there are present-day kid characteristics that weren't there in the past.

// 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