views:

143

answers:

3

I'm trying to create an XML document from a complex result set, i.e. a result set with multiple joins, so a competition has a bunch of questions, and a question has a bunch of answers.

So the document would end up looking something like:

<competitions>
  <competition id="12">
    <question id="3">
      <answer id="34">
        The answer
      </answer>
      <answer id="35">
        The answer
      </answer>
      <answer id="36">
        The answer
      </answer>
    </question>
...

A lot like the "for XML" command in SQL Server, but I can't use the database to do the processing, so it needs to be in Java. Can anyone point me in the right direction to any good resources or even open source libraries that do this / a similar thing so I can make it do what I want please? Thanks.

A: 

I don't understand from your question what "in Java" means? Do you need to parse this XML (use Dom4J), do you want to generate Java objects from this (use JAXB, or Xstream, or any of the other XML binding libraries), or do you need to write this XML?

Tbee
"in Java" means I can't use the database I have to use Java to do the processing. I need to create the XML from the returned resultset, I know how to manually create documents and elements etc. but am struggling when it comes to nested elements, like the XML example I gave.
marktucks
A: 

A reasonably easy thing would be to convert your result set first into a Competitions object then looks at converting the object into xml (using xstream or some such framework).

Are you able to convert your result set into a Competitions object ? (Or you want help in this, as well?)

class Competitions {
   List<Competition> getCompetitions();
}

class Competition {
   Integer getId();
   Question getQuestion();
}

class Question {
   Integer getId();
   Answer getAnswer();
}

class Answer {
   String getText();
}
Calm Storm
A: 

As Calm Storm suggested, I converted my result sets into an Object tree and created a custom toXml method in an Abstract Class, which traversed the methods in each object and created XML elements and attributes from them.

I just can't believe there isn't an easier Open Source solution for this, that would do all this automatically! Maybe I'm just lazy :)

marktucks
Hi to create a java object from result set you can use Hibernate (which is an ORM solution). Hibernate also has the option of XML export. But it is a bit tricky with joined result sets.
Calm Storm