HTML Agility Pack - 如何在Head元素顶部添加元素?

15

我想使用HTML Agility Pack将一个脚本元素添加到我的HTML头部的顶部。到目前为止,我看到的示例只是使用AppendChild(element)方法来实现这一点。我需要将我要附加到头部的脚本放在其他某些脚本之前。我该如何指定它的位置呢?

以下是我的尝试:

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的顶部,而不是追加到末尾。


1
提醒其他人,发现这个问题:stateScript.InnerHtml=...有时会对您的JavaScript产生奇怪的影响。为了解决这个问题,您可以改为使用stateScript.AppendChild(htmlDocument.CreateTextNode(scriptText)); - jp36
2个回答

20

意识到这是一个旧问题,还有一种可能性是在那时不存在的情况下添加子元素。

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

7

明白了...

HtmlNode有以下方法:

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

修改 HTML 源代码时要小心。它可能会更改其他部分的 HTML 代码,这些部分您可能不想触及 :/ - Oscar Mederos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接