﻿// Based on code by "christophilus".
// Article: http://www.codeproject.com/KB/ajax/XMLWriter.aspx

// This script needs the prototype.js java library.

function XMLWriter() {
    this.XML = [];
    this.Nodes = [];
    this.State = "";
    this.FormatXML = function(Str) {
        if (Str)
            return Str.toString().escapeHTML();
        return "";
    }
    this.BeginNode = function(Name) {
        if (!Name) return;
        if (this.State == "beg") this.XML.push(">");
        this.State = "beg";
        this.Nodes.push(Name);
        this.XML.push("<" + Name);
    }
    this.EndNode = function() {
        if (this.State == "beg") {
            this.XML.push("/>");
            this.Nodes.pop();
        }
        else if (this.Nodes.length > 0)
            this.XML.push("</" + this.Nodes.pop() + ">");
        this.State = "";
    }
    this.Attrib = function(Name, Value) {
        if (this.State != "beg" || !Name) return;
        this.XML.push(" " + Name + "=\"" + this.FormatXML(Value) + "\"");
    }
    this.WriteString = function(Value) {
        if (this.State == "beg") this.XML.push(">");
        this.XML.push(this.FormatXML(Value));
        this.State = "";
    }
    this.Node = function(Name, Value) {
        if (!Name) return;
        if (this.State == "beg") this.XML.push(">");
        this.XML.push((Value == "" || !Value) ? "<" + Name + "/>" : "<" + Name + ">" + this.FormatXML(Value) + "</" + Name + ">");
        this.State = "";
    }
    this.Close = function() {
        while (this.Nodes.length > 0)
            this.EndNode();
        this.State = "closed";
    }
    this.ToString = function() { return this.XML.join(""); }
}
