Changes on selected node reflected on the main document - htmlagilitypack

c# html-agility-pack local-variables selectsinglenode

Question

I am selecting a node with for example

HtmlDocument temp_HdDocument = new HtmlDocument();

temp_HdDocument.LoadHtml(mysource);

var vrTempNewNode = temp_HdDocument.SelectSingleNode("//a"));

I change node this way

foreach (HtmlNode node in vrTempNewNode.SelectNodes("*"))
{
    node.Remove();
}

Now when i make any changes on vrTempNewNode it is also reflected at temp_HdDocument

How can i prevent this happening ? I suppose select node just creates a reference object but i want it to be a new local variable not a part of main document

htmlagilitypack c# .net 4.5 wpf

Accepted Answer

That's the default behavior, and it's very handy in most case. You can use HtmlNode.CopyFrom() to create an independent copy of the existing node that you can then modify without affecting the original HtmlDocument, for example :

var a = temp_HdDocument.SelectSingleNode("//a"));
HtmlNode temp = HtmlNode.CreateNode("<a></a>");
temp.CopyFrom(a, false);



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