Inserting new node in html document in c#

c# html-agility-pack

Question

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 ?

Popular Answer

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why