HTML敏捷包 – 如何在Head元素的顶部追加元素?

我正在尝试使用HTML Agility Pack将脚本元素附加到我的html的HEAD部分的顶部。 到目前为止我看到的例子只是使用AppendChild(element)方法来实现这一点。 我需要将我附加到head部分的脚本放在其他脚本之前。 我怎么指定这个?

这是我正在尝试的:

 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\"}'"; 

我想在HEAD的顶部添加一个脚本标记,而不是在末尾附加。

意识到这是一个古老的问题,也有可能在那里预先存在可能不存在的子元素。

 // Load content as new Html document HtmlDocument html = new HtmlDocument(); html.LoadHtml(oldContent); // Wrapper acts as a root element string newContent = "
" + someHtml + "
"; // 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;

得到它了..

HtmlNode具有以下方法:

 HtmlNode.InsertBefore(node, refNode) HtmlNode.InsertAfter(nodeToAdd, refNode)