CSharp · Console
// @nuget: HtmlAgilityPack
using System;
using System.Xml;
using HtmlAgilityPack;
public class Program
{
public static void Main()
{
var html =
@"<body>
<h1>This is <b>bold</b> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
</body>";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
DisplayChildNodes(htmlBody);
HtmlNode h2Node = HtmlNode.CreateNode("<h2> This is h2 heading</h2>");
HtmlNode pNode1 = HtmlNode.CreateNode("<p> This is appended paragraph 1</p>");
HtmlNode pNode2 = HtmlNode.CreateNode("<p> This is appended paragraph 2</p>");
HtmlNodeCollection children = new HtmlNodeCollection(htmlBody);
children.Add(h2Node);
children.Add(pNode1);
children.Add(pNode2);
htmlBody.AppendChildren(children);
Console.WriteLine("\n****After children appended****\n");
DisplayChildNodes(htmlBody);
}
static void DisplayChildNodes(HtmlNode nodeElement)
{
HtmlNodeCollection childNodes = nodeElement.ChildNodes;
foreach (var node in childNodes)
{
if (node.NodeType == HtmlNodeType.Element)
{
Console.WriteLine(node.InnerText);
}
}
}
}