title: Covert database table result into XML - How to generate an XML document
body: <p>I have a query that when run returns a resultset with the following data in the order and grouping shown: </p>
  
  <pre><code>Country     Region      Town
  ---------------------------------------
  England     North       NewCastle
  England     North       Manchester
  England     North       Leeds
  England     South       London
  England     South       Bristol
  England     South       Birmingham
  England     South       Portsmouth
  Norway      North       Trondheim
  Norway      North       Tromso
  Norway      South       Oslo
  Norway      South       Stavanger
  Norway      West        Bergen
  </code></pre>
  
  <p>Using Java, i would like to convert the returned result into an XML document as shown below:</p>
  
  <pre><code>&lt;countries&gt;
      &lt;country&gt;
          &lt;countryName&gt;England&lt;/countryName&gt;
          &lt;region name = "south"&gt;
              &lt;town&gt;London&lt;/town&gt;
              &lt;town&gt;Bristol&lt;/town&gt;
              &lt;town&gt;Birmingham&lt;/town&gt;
              &lt;town&gt;Portsmouth&lt;/town&gt;
          &lt;/region&gt;
          &lt;region name = "north"&gt;
              &lt;town&gt;NewCastle&lt;/town&gt;
              &lt;town&gt;Leeds&lt;/town&gt;
          &lt;/region&gt;
      &lt;country&gt;
          &lt;country&gt;
          &lt;countryName&gt;Norway&lt;/countryName&gt;
          &lt;region name = "south"&gt;
              &lt;town&gt;Oslo&lt;/town&gt;
              &lt;town&gt;Stavanger&lt;/town&gt;
          &lt;/region&gt;
          &lt;region name = "west"&gt;
              &lt;town&gt;Bergen&lt;/town&gt;
          &lt;/region&gt;
          &lt;region name = "North"&gt;
              &lt;town&gt;Trondheim&lt;/town&gt;
              &lt;town&gt;Tromso&lt;/town&gt;
          &lt;/region&gt;       
      &lt;country&gt;
  &lt;countries&gt;
  </code></pre>
  
  <p>What is the best way to traverse the data so that the tags are created and closed at the correct position?  I have seen an example here <a href="http://www.mkyong.com/java/how-to-create-xml-file-in-java-jdom-parser/" rel="nofollow">http://www.mkyong.com/java/how-to-create-xml-file-in-java-jdom-parser/</a> but the structure of the data is flat unlike the sample i am using which will probably require multiple loops. </p>