convert a recursive structure to xml with jsp
https://stackoverflow.com/questions/1825113
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?
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.