Permalink
Browse files

Add geddy.utils.XML.stringify for XML output

  • Loading branch information...
1 parent cbdfdd4 commit 4547483e00dd9600c89588e2d75141c808ce088a Mike Ihbe committed Feb 14, 2012
Showing with 53 additions and 0 deletions.
  1. +2 −0 lib/utils/index.js
  2. +51 −0 lib/utils/xml.js
View
@@ -22,6 +22,7 @@ var geddy
, date = require('./date').date
, request = require('./request').request
, EventBuffer = require('./event_buffer').EventBuffer
+ , XML = require('./xml').XML
, SortedCollection = require('./sorted_collection').SortedCollection;
var utils = new (function () {
@@ -116,6 +117,7 @@ utils.date = date;
utils.request = request;
utils.SortedCollection = SortedCollection;
utils.EventBuffer = EventBuffer;
+utils.XML = XML;
module.exports = utils;
View
@@ -0,0 +1,51 @@
+/* This work is licensed under Creative Commons GNU LGPL License.
+
+ License: http://creativecommons.org/licenses/LGPL/2.1/
+ Version: 0.9
+ Author: Stefan Goessner/2006
+ Web: http://goessner.net/
+*/
+function json2xml(o, tab) {
+ var toXml = function(v, name, ind) {
+ var xml = "";
+ if (v instanceof Array) {
+ for (var i=0, n=v.length; i<n; i++)
+ xml += ind + toXml(v[i], name, ind+"\t") + "\n";
+ }
+ else if (typeof(v) == "object") {
+ var hasChild = false;
+ xml += ind + "<" + name;
+ for (var m in v) {
+ if (m.charAt(0) == "@")
+ xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
+ else
+ hasChild = true;
+ }
+ xml += hasChild ? ">" : "/>";
+ if (hasChild) {
+ for (var m in v) {
+ if (m == "#text")
+ xml += v[m];
+ else if (m == "#cdata")
+ xml += "<![CDATA[" + v[m] + "]]>";
+ else if (m.charAt(0) != "@")
+ xml += toXml(v[m], m, ind+"\t");
+ }
+ xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
+ }
+ }
+ else {
+ xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
+ }
+ return xml;
+ }, xml="";
+ for (var m in o)
+ xml += toXml(o[m], m, "");
+ return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
+}
+
+exports.XML = new function XML() {
+ this.stringify = function(o) {
+ return json2xml(o);
+ };
+};

0 comments on commit 4547483

Please sign in to comment.