加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:06:06 所属栏目:百科 来源:网络整理
导读:我试图使用 HTML Agility Pack将脚本元素附加到我的html的HEAD部分的顶部.到目前为止我已经看到的例子只是使用AppendChild(element)来完成这个.我需要我附加到头部的脚本来到一些其他脚本之前.我该如何指定? 这是我正在尝试的: HtmlDocument htmlDocument
我试图使用 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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读