2

假设我有以下 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);  

我得到System.StackOverflowExceptiondoc.DocumentNode.WriteContentTo().

可能的解决方案可能是这样的:

doc.LoadHtml("<html>" + doc.DocumentNode.WriteContentTo() + "</html>")

但由于完整的文档重新解析,它将无效。

你有什么想法,如何以高效的方式解决这个问题?

4

1 回答 1

3

最后,我让它工作了。第一个示例不起作用,因为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);  
于 2012-06-25T13:47:55.480 回答