1 /**
  2  * @fileoverview Class for XML serialization.
  3  */
  4 
  5 goog.provide('xrx.serialize');
  6 
  7 
  8 goog.require('xrx.stream');
  9 goog.require('xrx.token');
 10 
 11 
 12 
 13 xrx.serialize = {};
 14 
 15 
 16 
 17 xrx.serialize.indent = function(xml, indent) {
 18   var stream = new xrx.stream(xml);
 19   var level = 0;
 20   var lastRow = xrx.token.UNDEFINED;
 21   var lastToken = xrx.token.UNDEFINED;
 22   var output = '';
 23   
 24   var newLine = function(offset, length1, length2) {
 25     for(var i = 0, ind = level * indent; i < ind; i++) {
 26       output += ' ';
 27     }
 28     output += stream.xml().substr(offset, length1);
 29     if (length1 !== length2) {
 30       output += stream.xml().substr(offset + length1, length2 - length1);
 31     }
 32   };
 33   
 34   stream.rowStartTag = function(offset, length1, length2) {
 35     if (lastRow === xrx.token.START_TAG) level += 1;
 36     if (lastToken === xrx.token.START_TAG || lastToken === xrx.token.EMPTY_TAG) output += '\n';
 37     newLine(offset, length1, length2);
 38     lastRow = xrx.token.START_TAG;
 39     length1 !== length2 ? lastToken = xrx.token.NOT_TAG : 
 40         lastToken = xrx.token.START_TAG;
 41   };
 42   
 43   stream.rowEmptyTag = function(offset, length1, length2) {
 44     if(lastRow === xrx.token.START_TAG) level += 1;
 45     newLine(offset, length1, length2);
 46     lastRow = xrx.token.END_TAG;
 47     length1 !== length2 ? lastToken = xrx.token.NOT_TAG : 
 48       lastToken = xrx.token.EMPTY_TAG;
 49   };
 50   
 51   stream.rowEndTag = function(offset, length1, length2) {
 52     if (lastRow !== xrx.token.START_TAG) level -= 1;
 53     output += stream.xml().substr(offset, length1);
 54     if (level !== 0) output += '\n';
 55     lastRow = xrx.token.END_TAG;
 56     length1 !== length2 ? lastToken = xrx.token.NOT_TAG : 
 57       lastToken = xrx.token.END_TAG;
 58   };
 59   
 60   stream.forward();
 61   
 62   return output;
 63 };
 64