gpt4 book ai didi

c# - HTML Agility Pack - 如何在 Head 元素的顶部附加元素?

转载 作者:可可西里 更新时间:2023-11-01 07:53:53 25 4
gpt4 key购买 nike

我正在尝试使用 HTML Agility Pack 将脚本元素附加到我的 html 的 HEAD 部分的顶部。到目前为止,我看到的示例只是使用 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 的顶部,而不是附加在末尾。

最佳答案

意识到这是一个老问题,也有可能将当时可能不存在的子元素放在前面。

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

关于c# - HTML Agility Pack - 如何在 Head 元素的顶部附加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6011577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com