2011-05-15 82 views
13

我正在尝试使用HTML Agility Pack将脚本元素附加到我的html的HEAD部分的顶部。我迄今看到的例子只是使用AppendChild(element)方法来实现这一点。我需要将附加到头部的脚本放在其他脚本之前。我怎样才能指定这个?HTML Agility Pack - 如何在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\"}'"; 

我想朝着头,而不是附加在末尾的顶端增加了一个脚本标签。

+1

旁注其他人发现这个问题:'stateScript.InnerHtml = ...'有时会做你的javascript的奇怪的东西。要解决这个问题,你可以改为'stateScript.AppendChild(htmlDocument.CreateTextNode(scriptText));' – jp36 2012-04-02 16:11:16

回答

7

明白了..

HtmlNode有以下方法:

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

不要忘了勾选你的答案为“答案”。 – 2011-05-16 06:43:59

+0

修改HTML源代码时要小心。它可以改变可能不想触摸':/'的HTML代码的其他部分 – 2011-05-18 08:01:52

14

意识到这是一个老问题,也有在前面加上可能不会存在那么子元素的可能性。

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