views:

186

answers:

4

Let's say I have a recursive data structure

 class Tree {
      private Tree right;
      private Tree left;
      private int data;
      ....
 }

I want to convert it to xml with jsp, so my ui tree widget can load the xml page with Ajax and construct a tree (with expandable/collapsable nodes, etc).

The xml would look something like this:

<tree>
   <tree>
      <data value="5"/>
   </tree
   <tree>
      <data value="1"/>
      <tree>
          <data value="5"/>
      </tree
      <tree>
          <data value="1"/>
      </tree>
   </tree>
</tree>

Can such a recursive structure be generated with jsp? How?

+3  A: 

Try this:

class Tree {
     Tree right;
     Tree left;
     int data;

     public String toXmlString(){
        StringBuilder s = new StringBuilder();
        s.append("<tree>");
        s.append("<data value=\"" + data + "\" />");
        if(right != null)
            s.append(right.toXmlString());
        if(left != null)
            s.append(left.toXmlString());
        s.append("</tree>");

        return s.toString();
     }
 }

Some Usage:

Tree t = new Tree();
//fill values to tree
....

String xml = t.toXmlString();
jerjer
As simple as that. My suggestion of introducing a whole new set of libraries would have been a bad idea. +1
Adeel Ansari
Yeah right, we sometimes forget the simplier and easier way!!!
jerjer
Strictly speaking that's Java, not JSP.
Stephen C
@Stephen: Indeed, we rejected that idea in the first place altogether. :)
Adeel Ansari
A: 

Technically, I believe it could be done - probably with a custom tag. But JSPs are ill-suited for recursive algorithms.

Use a servlet and your XML API of choice (perhaps a StAX class like XMLStreamWriter).

McDowell
A: 

Although I appreciate the StringBuilder approach, I'd rather recommend using the java api for xml newbies. Using a StringBuilder is much faster but it's error prone also. Even if you know what you're doing, you should consider using javas builtin xml support, so you will not fall into the encoding trap.

dhiller
A: 

I hate to answer and accept my own question, but after reviewing the others, looks like the answer should be:

"Cannot reasonably be done with JSP".

flybywire