title: Javascript Objects to XML String with multiple levels
body: <p>I have a multi-dimensional Javascript Object that I can easily convert to a JSON string using a .stringify method.  I'm trying to write a function to do something similar but in an XML, markup, format.  The catch is I want it to be able to handle any number of dimensions.</p>
  
  <p>Let's say I have the following the multi-dimensional object with values like so:</p>
  
  <pre><code>object['annualrevenues']['option0']['ID'] = 1;
  object['annualrevenues']['option0']['text'] = '$50mil';
  object['annualrevenues']['option1']['ID'] = 2;
  object['annualrevenues']['option1']['text'] = '$100mil';
  object['annualrevenues']['option2']['ID'] = 3;
  object['annualrevenues']['option2']['text'] = '$200mil';
  </code></pre>
  
  <p>I want to build a string like so:</p>
  
  <pre><code>var xmlText = &lt;xml&gt;&lt;annualrevenues&gt;&lt;option0&gt;&lt;ID&gt;1&lt;/ID&gt;&lt;text&gt;$50&lt;/text&gt;&lt;/option0&gt;&lt;/annualrevenues&gt;&lt;/xml&gt;
  </code></pre>
  
  <p>That once returned as a response with contentType 'XMLDOC' will look like this:   </p>
  
  <pre><code>&lt;xml&gt;
    &lt;annualrevenues&gt;
      &lt;option0&gt;
        &lt;ID&gt;1&lt;/ID&gt;
        &lt;text&gt;$50&lt;/text&gt;
      &lt;/option0&gt;
    &lt;/annualrevenues&gt;
  &lt;/xml&gt;
  </code></pre>
  
  <p>So I have the following function:</p>
  
  <pre><code>var xmlText = '&lt;xml&gt;';
      xmlText += formatXMLSubObjects(objText,xmlText);
  
  function formatXMLSubObjects(objText,xmlText){
    for (prop in objText) {
      if (typeof objText[prop] == 'object') {
          xmlText += '&lt;'+prop+'&gt;';
          for (subProp in objText[prop]) {
              if (typeof objText[prop][subProp] == 'object') {
                  // Run the function again as recursion
                  xmlText += formatXMLSubObjects(objText[prop][subProp],xmlText);
              }
              else {
                  xmlText += '&lt;' + subProp + '&gt;' + objText[prop][subProp] + '&lt;/' + subProp + '&gt;';
              }
          }
          xmlText += '&lt;/'+prop+'&gt;';
      }
      else {
          xmlText += '&lt;'+prop+'&gt;'+objText[prop]+'&lt;/'+prop+'&gt;';
      }
    }
  return xmlText;
  }
  </code></pre>
  
  <p>The problem is when the formatXMLSubObjects function returns from the second call, the original object in the first call has been overwritten and is now undefined.</p>
  
  <p>Anyone able to help with this?</p>