如何在HtmlAgilityPack中替换/添加根元素?

时间:2012-06-25 09:15:37

标签: c# html html-agility-pack

假设我有以下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.StackOverflowException之后得到doc.DocumentNode.WriteContentTo()

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

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

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

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

1 个答案:

答案 0 :(得分:2)

最后,我得到了它的工作。第一个示例无效,因为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);