Replace a single node with multiple nodes using the HTML Agility Pack

I have an input tag, which are placeholders, which I replace with some HTML. Many times when I replace them with HTML, this is just one tag that is simple enough:

HtmlNode node = HtmlNode.CreateNode(sReplacementString); inputNode.ParentNode.ReplaceChild(node, inputNode); 

However, if I want to replace inputNode with two or more HtmlNode.CreateNode(sReplacementString) nodes, then only the first node. Is there a way to make a replacement where sReplacementString is multiple tags?

+4
source share
1 answer

As far as I know, there is no direct way to do this. HtmlNode.CreateNode method creates a single node from an HTML fragment, if there are several nodes, the first one is created only.

As a workaround, you can create a temporary node, create its child nodes from sReplacementString , and then add these child nodes immediately after the inputNode node and finally delete the inputNode .

 var temp = doc.CreateElement("temp"); temp.InnerHtml = sReplacementString; var current = inputNode; foreach (var child in temp.ChildNodes) { inputNode.ParentNode.InsertAfter(child, current); current = child; } inputNode.Remove(); 
+5
source

Source: https://habr.com/ru/post/1401439/


All Articles