Running into an odd issue, and not too sure why. Dumbed down code is below, having a simple console project with the below code will cause it to happen in my dev system:
static void Main(string[] args)
{
//Create blank document, get references to head and body.
var output = new HtmlDocument();
output.LoadHtml("<!DOCTYPE html>" + Environment.NewLine + "<html lang='en'><head></head><body></body></html>");
var outputHead = output.DocumentNode.SelectSingleNode("//head");
var outputBody = output.DocumentNode.SelectSingleNode("//body");
//Open original document, copy over our HEAD.
var siToc = new HtmlDocument();
siToc.Load("SITOC.html");
// At this point, siToc.DocumentNode.SelectNodes("//html/body/*") - has count 3. Expected.
outputBody.AppendChild(siToc.DocumentNode.SelectSingleNode("/html/body/div[@class=\"page_header\"]"));
// At this point, siToc.DocumentNode.SelectNodes("//html/body/*") now only has 1 - the one I added to the outputBody.
}
The issue is specifically that my source document is seemingly getting overwritten in memory when I try adding one of its nodes to my output document. I initially thought that it may be because there's a reference to the source document's parent there, and that's getting put in (and replacing) what my output document has. However, I can't seem to set the parent to null, no I'm not sure I'm on the right track there.
Do I need to create a clone or something of the nodes/elements I want to bring over?
Was asked for a sample "SITOC.HTML". Note that any HTML document would cause this in my testing, but to reference the code above, the following HTML will work, and cause it to occur. This happens in .NET 5.0, under VS2022, using the latest version of HtmlAgilityPack that is available on NuGet.
<!DOCTYPE html>
<html lang='en'>
<head>
</head>
<body>
<div class="page_header">Text</div>
<div class="page_footer">Text</div>
<section>
<div class="some class">Text</div>
</section>
</body>
</html>