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?
我正在尝试使用HTML Agility Pack将脚本元素附加到我的html的HEAD部分的顶部。到目前为止我看到的例子只是使用AppendChild(element)方法来实现这一点。我需要将我附加到head部分的脚本放在其他脚本之前。我怎么指定这个?
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.
我想在HEAD的顶部添加一个脚本标记,而不是在末尾附加。
2 个解决方案
#1
16
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;
#2
7
Got it..
HtmlNode has the following methods:
HtmlNode具有以下方法:
HtmlNode.InsertBefore(node, refNode)
HtmlNode.InsertAfter(nodeToAdd, refNode)
#1
16
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;
#2
7
Got it..
HtmlNode has the following methods:
HtmlNode具有以下方法:
HtmlNode.InsertBefore(node, refNode)
HtmlNode.InsertAfter(nodeToAdd, refNode)