I have some input tags that are placeholders that I am replacing with some HTML. A lot of the time the HTML I'm replacing them with is only one tag, which is easy enough:

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

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

  • Can you provide more context? You might be able to replace the node with a div containing your 2 children or something like that. – Steve Danner Mar 14 '12 at 18:25
  • @SteveDanner I don't want any extra markup. inputNode.ParentNode could be anything, hence the need for the replace function to work! – Jon Mar 14 '12 at 18:28

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

As a workaround you could create a temporary node, create its child nodes from the sReplacementString, and then append these child nodes right after the inputNode node, and, finally, remove 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;
  • Spot on, though I didn't have a Remove function so I used inputNode.ParentNode.RemoveChild(inputNode); – Jon Mar 15 '12 at 8:10
  • Was exactly what I needed, I spent a long time thinking this would be an existing method, but seems with HtmlAgilityPack there are random things you need to write for yourself quite often. – Colin Asquith Aug 23 '12 at 14:17

Your Answer

