// CppNavigator.cpp : main project file.

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

using namespace System;
using namespace System::Xml;
using namespace System::Xml::XPath;

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} path", args[0]);
		return -1;
	}

	String^ path = gcnew String(args[1]);

	try
	{
		// Create the XmlDocument to parse the file
		XmlDocument^ doc = gcnew XmlDocument();

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

		// Create the navigator
		XPathNavigator^ nav = doc->CreateNavigator();

		// Move to the top of the tree and print details
		nav->MoveToRoot();
		Console::WriteLine(L"top: name={0}, \ntype={1}, \nvalue={2} \n",
			nav->Name, ((Object^)(nav->NodeType))->ToString(), nav->Value);
		Console::WriteLine();

		// Move to the first child, which is a comment
		nav->MoveToFirstChild();
		Console::WriteLine(L"first child: name={0}, type={1}",
                   nav->Name, ((Object^)(nav->NodeType))->ToString());
		// Move to the next element, which is the root element
		nav->MoveToNext();
		Console::WriteLine(L"next child: name={0}, type={1}",
                   nav->Name, ((Object^)(nav->NodeType))->ToString());
		// Move to the next element, which will be the first
		// volcano
		nav->MoveToFirstChild();
		Console::WriteLine(L"next child: name={0}, type={1}",
                   nav->Name, ((Object^)(nav->NodeType))->ToString());
		if (nav->HasAttributes)
		{
			nav->MoveToFirstAttribute();
			Console::WriteLine(L" attribute: name={0}, type={1}",
				nav->Name, nav->Value);
			 nav->MoveToParent();
		}

		// Move back to the root
		Console::WriteLine(L"XPath test...");
		nav->MoveToRoot();

		// Select all ’volcano’ elements that are children of ’geology’
		// and have a ’comment’ child, starting at the root
		XPathNodeIterator^ xpi = nav->Select(L"/geology/volcano[comment]");
		Console::WriteLine(L"Select returned {0} nodes",
			(Object^)(xpi->Count));

		while (xpi->MoveNext())
		{
			XPathNavigator^ xpn = xpi->Current;
			Console::Write(L"node: name={0}, type={1}", xpn->Name,
				((Object^)(xpn->NodeType))->ToString());
			xpn->MoveToFirstAttribute();
			Console::WriteLine(L", name={0}", xpn->Value);
		}
	}
	catch(Exception^ pe)
	{
		Console::WriteLine(pe->Message);
	}

	return 0;
}
