Question

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?

Was it helpful?

Solution 2

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".

OTHER TIPS

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();

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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top