// CppDom.cpp : main project file.

#include "stdafx.h"
#using <System.xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Collections;

ref class XmlBuilder
{
    XmlDocument^ doc;
	public:
    XmlBuilder(String^ path)
    {
        // Create the XmlDocument
        doc = gcnew XmlDocument();

        // Load the data
        doc->Load(path);
        Console::WriteLine(L"Document loaded");

		// Get the root of the tree
		root = doc->DocumentElement;

		// get the child node list
		xnl = doc->ChildNodes;
		IEnumerator^ ie = xnl->GetEnumerator();
		 
		while (ie->MoveNext() == true)
			Console::WriteLine(L"Child: {0}",
		(dynamic_cast<XmlNode^>(ie->Current))->Name);
    }

	void ProcessChildNodes()
	{
		// Declare an enumerator
		IEnumerator^ ie = xnl->GetEnumerator();

		while (ie->MoveNext() == true)
		{
			// Get a pointer to the node
			XmlNode^ pNode = dynamic_cast<XmlNode^>(ie->Current);

			// See if it is the root
			if (pNode->NodeType == XmlNodeType::Element &&
				pNode->Name->Equals(L"geology"))
			{
				Console::WriteLine(L"  Found the root");
				ProcessRoot(pNode);
			}
		}
	}

	void ProcessRoot(XmlNode^ rootNode)
	{
		XmlNode^ pVolc = dynamic_cast<XmlNode^>(rootNode->ChildNodes->Item(1));

		// Create a new volcano element
		XmlElement^ newVolcano = CreateNewVolcano();

		// Link it in
		root->InsertBefore(newVolcano, pVolc);
	}

	XmlElement^ CreateNewVolcano()
	{
		// Create a new element
		XmlElement^ newElement = doc->CreateElement(L"volcano");

		// Set the name attribute
		XmlAttribute^ pAtt = doc->CreateAttribute(L"name");
		pAtt->Value = L"Mount St.Helens";
		newElement->Attributes->Append(pAtt);

		// Create the location element
		XmlElement^ locElement = doc->CreateElement(L"location");
		XmlText^ xt = doc->CreateTextNode(L"Washington State, USA");
		locElement->AppendChild(xt);

		newElement->AppendChild(locElement);

		return newElement;
	}

	void PrintTree()
	{
		XmlTextWriter^ xtw = gcnew XmlTextWriter(Console::Out);
		xtw->Formatting = Formatting::Indented;

		doc->WriteTo(xtw);
		xtw->Flush();
		Console::WriteLine();
	}




	private:
		XmlNode^ root;
		XmlNodeList^ xnl;
};

int main(array<System::String ^> ^args)
{
    // Get the command line arguments
	args = Environment::GetCommandLineArgs();

	// Check for required arguments
	if (args->Length < 2)
	{
		Console::WriteLine(L"Usage: {0:s} path", args[0]);
		return -1;
	}
	String^ path = gcnew String(args[1]);

	// Create a Builder and get it to read the file
	try
	{
		XmlBuilder^ pf = gcnew XmlBuilder(path);
		pf->ProcessChildNodes();

		pf->PrintTree();
	}
	catch(Exception^ pe)
	{
		Console::WriteLine(pe->Message);
	}
	return 0;
}

