Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to combine nodes with Html Agility Pack
    primarykey
    data
    text
    <p>I've converted a large document from Word to HTML. It's close, but I have a bunch of "code" nodes that I'd like to merge into one "pre" node.</p> <p>Here's the input:</p> <pre><code>&lt;p&gt;Here's a sample MVC Controller action:&lt;/p&gt; &lt;code&gt; public ActionResult Index()&lt;/code&gt; &lt;code&gt; {&lt;/code&gt; &lt;code&gt; return View();&lt;/code&gt; &lt;code&gt; }&lt;/code&gt; &lt;p&gt;We'll start by making the following changes...&lt;/p&gt; </code></pre> <p>I want to turn it into this, instead:</p> <pre><code>&lt;p&gt;Here's a sample MVC Controller action:&lt;/p&gt; &lt;pre class="brush: csharp"&gt; public ActionResult Index() { return View(); }&lt;/pre&gt; &lt;p&gt;We'll start by making the following changes...&lt;/p&gt; </code></pre> <p>I ended up writing a brute-force loop that iterates nodes looking for consecutive ones, but this seems ugly to me:</p> <pre><code>HtmlDocument doc = new HtmlDocument(); doc.Load(file); var nodes = doc.DocumentNode.ChildNodes; string contents = string.Empty; foreach (HtmlNode node in nodes) { if (node.Name == "code") { contents += node.InnerText + Environment.NewLine; if (node.NextSibling.Name != "code" &amp;&amp; !(node.NextSibling.Name == "#text" &amp;&amp; node.NextSibling.NextSibling.Name == "code") ) { node.Name = "pre"; node.Attributes.RemoveAll(); node.SetAttributeValue("class", "brush: csharp"); node.InnerHtml = contents; contents = string.Empty; } } } nodes = doc.DocumentNode.SelectNodes(@"//code"); foreach (var node in nodes) { node.Remove(); } </code></pre> <p>Normally I'd remove the nodes in the first loop, but that doesn't work during iteration since you can't change the collection as you iterate over it.</p> <p>Better ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload