Z.Example.CopyFrom

CSharp · Console

/Program.cs

// @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");
		
		HtmlNode newBody = HtmlNode.CreateNode("<body></body>");
            
        newBody.CopyFrom(htmlBody);
		
		DisplayNode(htmlBody);
	
        Console.WriteLine("\n****Duplicate node****\n");
		
		DisplayNode(newBody);
	}
	
	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);
				}
        	}
		}
    }
}
;