假設我有以下HTML代碼:
<p>Hello, bla-bla-bla</p>
<a href="somesite">Click here</a>
如您所見,它沒有html / body標籤。我想要做的是在文檔的頂部添加html和body標籤。
我嘗試使用以下代碼添加html標記:
var el = doc.CreateElement("html");
var nodes = doc.DocumentNode.ChildNodes;
doc.DocumentNode.RemoveAllChildren();
el.AppendChildren(nodes);
doc.DocumentNode.AppendChild(el);
但之後,調用doc.DocumentNode.WriteContentTo()
返回<html></html>
。如果我更改最後一行的執行順序:
var el = doc.CreateElement("html");
var nodes = doc.DocumentNode.ChildNodes;
doc.DocumentNode.RemoveAllChildren();
doc.DocumentNode.AppendChild(el);
el.AppendChildren(nodes);
我在doc.DocumentNode.WriteContentTo()
之後得到了System.StackOverflowException
。
可能的解決方案可能是這樣的:
doc.LoadHtml("<html>" + doc.DocumentNode.WriteContentTo() + "</html>")
但由於完整的文件重新分析,它將無效。
您有什麼想法,如何以性能有效的方式解決這個問題?
最後,我得到了它的工作。第一個樣品不工作,因為doc.DocumentNode.ChildNodes
不是返回副本HtmlNodeCollection
,但節點集合本身。它導致所有收集的節點在添加到el
之前被刪除。下面的代碼可以解決問題:
var el = doc.CreateElement("html");
var nodes = doc.DocumentNode.ChildNodes;
el.AppendChildren(nodes);
doc.DocumentNode.RemoveAllChildren();
doc.DocumentNode.AppendChild(el);