0

I am trying to insert new node in the document using htmlagilitypack. I am reading the document from the stream , insert the node and then return the document as a FileContentResult object :

HtmlDocument ndoc = new HtmlDocument();
ndoc.Load(stream);

HtmlNode usern = HtmlNode.CreateNode("<img .... />");
usern.Attributes.Add("onclick", "javascript:document.location.href='/Home/Index';");
ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern);

using (MemoryStream ms = new MemoryStream())
{
   ndoc.Save(ms);
   ms.Seek(0, System.IO.SeekOrigin.Begin);
   fileBytes = ms.ToArray();
}

FileContentResult file = File(fileBytes, "text/html");
return file;

Problem : New node ( img ) is not inserting. My footer content gone if i am using this code and if i just read the document from the stream and return as a FileContentResult then everything perfect. I want to know whats the problem with this code or where i am doing wrong ?

King Kong
  • 2,855
  • 5
  • 28
  • 39

3 Answers3

0

Take a look at HTML Agility pack create new HTMLNode.

This shows how to properly create a new node. In my experience, their code works fine. Similar to jQuery taking it step by step. Good luck!

Community
  • 1
  • 1
jamesbar2
  • 614
  • 1
  • 9
  • 20
0

try to change

HtmlNode usern = HtmlNode.CreateNode("<img .... />");

to just img

HtmlNode usern = HtmlNode.CreateNode("<img></img>");

and add this

 ndoc.OptionWriteEmptyNodes = true;
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

I came across the same issue, resolved it by passing the clone object. just modify the line

ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern);

to

ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern.CloneNode(true));
Naga
  • 2,368
  • 3
  • 23
  • 33