﻿function CXmlWriter()
{
	this.aXml = [];
	this.aNodes = [];
	this.State = "";
	this.FormatXml = function(Value)
	{
		if (Value)
			return Value.replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
			
		return ""
	}
	this.WriteStartElement = function(Name)
	{
		if (!Name) return;

		if (this.State == "Begin")
			this.aXml.push(">");

		this.State = "Begin";
		this.aNodes.push(Name);
		this.aXml.push("<" + Name);
	}
	this.WriteEndElement = function()
	{
		if (this.State == "Begin")
		{
			this.aXml.push("/>");
			this.aNodes.pop();
		}
		else if (this.aNodes.length > 0)
		{
			this.aXml.push("</" + this.aNodes.pop() + ">");
		}
		
		this.State = "";
	}
	this.WriteAttributeString = function(Name, Value)
	{
		if (this.State != "Begin" || !Name)
			return;
			
		this.aXml.push(" " + Name + "=\"" + this.FormatXml(Value) + "\"");
	}
	this.WriteString = function(Value)
	{
		if (this.State == "Begin")
			this.aXml.push(">");
			
		this.aXml.push(this.FormatXml(Value));
		this.State = "";
	}
	this.Close = function()
	{
		if (this.aNodes.length > 0)
		{
			var Name = this.aNodes.pop();
			throw (Name + " Node still opened.");
		}

		this.State = "Closed";
	}
	this.ToString = function()
	{
		if (this.State != "Closed")
			throw ("Not closed");

		return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
			+ this.aXml.join("");
	}
}
