Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Agility Pack - How can append element at the top of Head element?

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();
htmlDocument.Load(filePath);
HtmlNode head = htmlDocument.DocumentNode.SelectSingleNode("/html/head");
HtmlNode stateScript = htmlDocument.CreateElement("script");
head.AppendChild(stateScript);
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.

like image 888
Nick Avatar asked May 15 '11 22:05

Nick


2 Answers

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();
html.LoadHtml(oldContent);

// 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
body.PrependChild(newNode);

// Get contents with new node
string contents = html.DocumentNode.InnerHtml;
like image 89
Joel Peltonen Avatar answered Nov 19 '22 01:11

Joel Peltonen


Got it..

HtmlNode has the following methods:

HtmlNode.InsertBefore(node, refNode)
HtmlNode.InsertAfter(nodeToAdd, refNode)
like image 41
Nick Avatar answered Nov 19 '22 02:11

Nick