title: How to create hierachical xml generically
body: <p>I need to be able to output hierarchical XML from SQL but I'd prefer not to have to create similar functions for each required schema.</p>
  
  <p>For example, given data that looks like this:</p>
  
  <pre><code>+----+----------+----------------------------------------------------------+
  | ID | ParentID |                           XML                            |
  +----+----------+----------------------------------------------------------+
  |  1 | NULL     | &lt;root/&gt;                                                  |
  |  2 | 1        | &lt;A someattr="whatever"&gt;some text&lt;/A&gt;                     |
  |  3 | 1        | &lt;B someattr="stuff"&gt;more text &lt;and&gt;&lt;elements/&gt;&lt;/and&gt;&lt;/B&gt; |
  |  4 | 3        | &lt;B1&gt;Child of B&lt;/B1&gt;                                      |
  |  5 | 4        | &lt;B1A/&gt;                                                   |
  |  6 | 2        | &lt;Child_Of-A/&gt;                                            |
  +----+----------+----------------------------------------------------------+
  </code></pre>
  
  <p>We should have an output that looks like this:</p>
  
  <pre><code>&lt;root&gt;
    &lt;A someattr="whatever"&gt;some text&lt;Child_Of-A /&gt;&lt;/A&gt;
    &lt;B someattr="stuff"&gt;more text&lt;and&gt;&lt;elements /&gt;&lt;/and&gt;
      &lt;B1&gt;Child of B&lt;B1A /&gt;
      &lt;/B1&gt;
    &lt;/B&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>(or semantically the same as)</p>
  
  <p>There are plenty of posts on the internet explaining how to do this non-dynamically, but I couldn't find any generic solutions.</p>
  
  <p>How can it be done without creating a new function (or set of) for each schema?</p>