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");
DisplayNode(htmlBody);
HtmlNode newPara = HtmlNode.CreateNode("<p>This a new paragraph</p>");
htmlBody.ChildNodes.Add(newPara);
Console.WriteLine("\n****After adding new child node****\n");
DisplayNode(htmlBody);
}
static void DisplayNode(HtmlNode node)
{
Console.WriteLine("Node Name: " + node.Name);
Console.Write("\n" + node.Name + " children:\n");
DisplayChildNodes(node);
}
static void DisplayChildNodes(HtmlNode nodeElement)
{
HtmlNodeCollection childNodes = nodeElement.ChildNodes;
if (childNodes.Count == 0)
{
Console.WriteLine(nodeElement.Name + " has no children");
}
else
{
foreach (var node in childNodes)
{
if (node.NodeType == HtmlNodeType.Element)
{
Console.WriteLine(node.OuterHtml);
}
}
}
}
}