HTML敏捷性包 - 如何可以在头元件的顶部添加元素? [英] HTML Agility Pack - How can append element at the top of Head element?

查看:133
本文介绍了HTML敏捷性包 - 如何可以在头元件的顶部添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用HTML敏捷性包追加一个脚本元素插入我的HTML的HEAD部分的顶部。我所看到的例子,到目前为止仅仅使用的appendChild(元素)的方法来做到这一点。我需要,我附加到头部部分来一些其他脚本之前的脚本。我怎么可以指定此?

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?

下面就是我想:

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.

推荐答案

意识到这是一个老问题,也有prepending子元素,可能不会再存在的可能性。

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;

这篇关于HTML敏捷性包 - 如何可以在头元件的顶部添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆