title: Pretty printing XML with javascript
body: <p>I have a string that represents a non indented XML that I would like to pretty-print. For example:</p>
  
  <pre><code>&lt;root&gt;&lt;node/&gt;&lt;/root&gt;
  </code></pre>
  
  <p>should become:</p>
  
  <pre><code>&lt;root&gt;
    &lt;node/&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then use a <a href="http://www.w3.org/TR/html401/struct/text.html#h-9.3.4" rel="noreferrer"><em>pre</em></a> tag to output the XML. To add new lines and white spaces I wrote the following function: </p>
  
  <pre><code>function formatXml(xml) {
      var formatted = '';
      var reg = /(&gt;)(&lt;)(\/*)/g;
      xml = xml.replace(reg, '$1\r\n$2$3');
      var pad = 0;
      jQuery.each(xml.split('\r\n'), function(index, node) {
          var indent = 0;
          if (node.match( /.+&lt;\/\w[^&gt;]*&gt;$/ )) {
              indent = 0;
          } else if (node.match( /^&lt;\/\w/ )) {
              if (pad != 0) {
                  pad -= 1;
              }
          } else if (node.match( /^&lt;\w[^&gt;]*[^\/]&gt;.*$/ )) {
              indent = 1;
          } else {
              indent = 0;
          }
  
          var padding = '';
          for (var i = 0; i &lt; pad; i++) {
              padding += '  ';
          }
  
          formatted += padding + node + '\r\n';
          pad += indent;
      });
  
      return formatted;
  }
  </code></pre>
  
  <p>I then call the function like this:</p>
  
  <pre><code>jQuery('pre.formatted-xml').text(formatXml('&lt;root&gt;&lt;node1/&gt;&lt;/root&gt;'));
  </code></pre>
  
  <p>This works perfectly fine for me but while I was writing the previous function I thought that there must be a better way. So my question is do you know of any better way given an XML string to pretty-print it in an html page? Any javascript frameworks and/or plugins that could do the job are welcome. My only requirement is this to be done on the client side.</p>