-
-
Notifications
You must be signed in to change notification settings - Fork 395
Open
Description
Let's say I have an HtmlDocument that has some child nodes in DocumentNode like <div></div><div></div><div></div>
. I want to encapsulate the existing childs into a new <html></html>
Node:
private void InsertHtmlRootElement(HtmlDocument doc) {
HtmlNode HtmlTag = doc.DocumentNode.ChildNodes.FindFirst("html");
if (HtmlTag is null) {
// Create new <html></html> Node
HtmlTag = new HtmlNode(HtmlNodeType.Element, doc, 0) { Name = "html" };
// Move all childs from root into the new HTML Node
HtmlTag.MoveChildren(doc.DocumentNode.ChildNodes);
// Append new HTML Node into Document
doc.DocumentNode.AppendChild(HtmlTag);
// HtmlTag.ChildNodes.ForEach(c => c.SetParent(HtmlTag));
}
}
This works but all children of HtmlTag have their ParentNode set to null. I guessed that I first need to add the HtmlTag to the document and then insert the childs to fix it:
private void InsertHtmlRootElement(HtmlDocument doc) {
HtmlNode HtmlTag = doc.DocumentNode.ChildNodes.FindFirst("html");
if (HtmlTag is null) {
// Append new <html></html> Node
HtmlTag = new HtmlNode(HtmlNodeType.Element, doc, 0) { Name = "html" };
doc.DocumentNode.AppendChild(HtmlTag);
// Move all childs from root into the new HTML Node
doc.DocumentNode.ChildNodes.Except([HtmlTag]).ToArray().ForEach( c => {
HtmlTag.MoveChild(c);
// c.SetParent(HtmlTag);
});
}
}
As it turns out, the children still have no parent. To work around that, I have to call c.SetParent(HtmlTag);
explicitly.
Metadata
Metadata
Assignees
Labels
No labels