HtmlAgilityPack替换节点

我想用新节点替换节点。 如何获取节点的确切位置并完全替换?

我已经尝试了以下内容,但我无法弄清楚如何获取节点的索引或哪个父节点调用ReplaceChild()

 string html = "bold_onestrongbold_two"; HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); var bolds = document.DocumentNode.Descendants().Where(item => item.Name == "b"); foreach (var item in bolds) { string newNodeHtml = GenerateNewNodeHtml(); HtmlNode newNode = new HtmlNode(HtmlNodeType.Text, document, ?); item.ParentNode.ReplaceChild( ) } 

要创建新节点,请使用HtmlNode.CreateNode()工厂方法,不要直接使用构造函数。

这段代码应该适合你:

 var htmlStr = "bold_onestrongbold_two"; var doc = new HtmlDocument(); doc.LoadHtml(htmlStr); var query = doc.DocumentNode.Descendants("b"); foreach (var item in query.ToList()) { var newNodeStr = "bar"; var newNode = HtmlNode.CreateNode(newNodeStr); item.ParentNode.ReplaceChild(newNode, item); } 

请注意,我们需要在查询上调用ToList() ,我们将修改文档,这样如果不这样做就会失败。


如果你想用这个字符串替换:

 "some text node another node" 

问题是它不再是单个节点而是一系列节点。 您可以使用HtmlNode.CreateNode()解析它,但最后,您只是引用序列的第一个节点。 您需要使用父节点进行替换。

 var htmlStr = "bold_onestrongbold_two"; var doc = new HtmlDocument(); doc.LoadHtml(htmlStr); var query = doc.DocumentNode.Descendants("b"); foreach (var item in query.ToList()) { var newNodesStr = "some text node another node"; var newHeadNode = HtmlNode.CreateNode(newNodesStr); item.ParentNode.ReplaceChild(newHeadNode.ParentNode, item); } 

我正在为新生成的节点使用HtmlDocument.DocumentNode

 string html = "bold_onestrongbold_two"; HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); var bolds = document.DocumentNode.Descendants().Where(item => item.Name == "b"); foreach (var item in bolds) { string newNodeHtml = GenerateNewNodeHtml(); var nodeDocument = new HtmlDocument(); nodeDocument.LoadHtml(newNodeHtml); item.ParentNode.ReplaceChild(nodeDocument.DocumentNode); }