HtmlAgilityPack - Replace Node With Another Node

asp.net c# html-agility-pack vb.net

Question

The inner HTML of my two nodes reads something like this:

Node1:

<p>some text</p>
<p>some more text</p>

Node2:

<p>some text</p>
<p>some more text</p>
<div><p>lots of more paragraphs here</p></div>

In order to add, I'm attempting to search for Node1 in Node2.<!--more--> tag (for WordPress articles) after the first two sentences (or whatever HTML text is supplied in Node1).

The parents of the two aforementioned nodes vary. How can I locate the replacement or addition of the<!--more--> tag in this scenario? I attempted to execute the code below, but it fails:

Code:

node2.ParentNode.ReplaceChild(HtmlNode.CreateNode(node1.InnerHtml & "<!--more-->"), node1).InnerHtml

Error:

Node "

             " was not found in the collection
Parameter name: node

Likewise, changednode1 the oldChild portion ofHtmlNode.CreateNode(node1.InnerHtml) yet even that didn't succeed.

1
0
8/22/2012 6:12:21 PM

Accepted Answer

I believe replacing would be simpler to do onHtmlNode.InnerHtml property specifically:

node2.InnerHtml = node2.InnerHtml.Replace(
    node1.InnerHtml, 
    node1.InnerHtml + "<!--more-->"
);
3
8/22/2012 10:01:11 PM

Popular Answer

I'm not sure why replacing doesn't work, however you may use the InsertAfter Method.

const string html = @"<p>some text</p>
<p>some more text</p>
<div><p>lots of more paragraphs here</p></div>";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var secondParagraph = doc.DocumentNode.SelectSingleNode("//p[2]");
// var secondParagraph = doc.DocumentNode.Descendants("p").Skip(1).First(); //or Linq
var moreNode= HtmlNode.CreateNode("<!--more-->");
doc.DocumentNode.InsertAfter(moreNode,secondParagraph );


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow