Nic*_*ick 14 .net c# html-agility-pack asp.net-mvc-2
我正在尝试使用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\"}'";
Run Code Online (Sandbox Code Playgroud)
我想在HEAD的顶部添加一个脚本标记,而不是在末尾附加.
Nen*_*lep 16
意识到这是一个古老的问题,也有可能在那里预先存在可能不存在的子元素.
// 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;
Run Code Online (Sandbox Code Playgroud)
得到它了..
HtmlNode具有以下方法:
HtmlNode.InsertBefore(node, refNode)
HtmlNode.InsertAfter(nodeToAdd, refNode)
Run Code Online (Sandbox Code Playgroud)