2011-05-15 34 views
13

Estoy tratando de usar HTML Agility Pack para agregar un elemento de script en la parte superior de la sección HEAD de mi html. Los ejemplos que he visto hasta ahora solo usan el método AppendChild(element) para lograr esto. Necesito que la secuencia de comandos que agrego a la sección principal venga antes que otras secuencias de comandos. ¿Cómo puedo especificar esto?HTML Agility Pack: ¿cómo se puede agregar un elemento en la parte superior del elemento principal?

Aquí es lo que estoy tratando:

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\"}'"; 

me gustaría una etiqueta de script que se añade a la parte superior de la cabeza en lugar de adjunta al final.

+1

Considere a otros encontrando esta pregunta: 'stateScript.InnerHtml = ...' a veces hará cosas raras a su javascript. Para solucionar esto, puede hacer 'stateScript.AppendChild (htmlDocument.CreateTextNode (scriptText));' – jp36

Respuesta

7

Entendido ..

HtmlNode tiene los siguientes métodos:

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

No olvide marcar su respuesta como "la". –

+0

Tenga cuidado al modificar la fuente HTML. Puede cambiar otras partes del código HTML que tal vez no desee tocar ': /' –

14

Al darse cuenta de que esto es una cuestión de edad, también existe la posibilidad de anteponiendo elementos secundarios que podrían no haber existido entonces.

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