Convert JTree to XML
I've seen many many articles on how to read XML into a JTree but few on how to cre开发者_如何学编程ate the XML from the JTree. Can anyone help me with a simple approach for this? I've seen an example that looked like:
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream(f.toString())));
e.writeObject(o);
e.close();
.. but I can't get this to work; it returns an XML file but its not quite right, looking like this:
<java version="1.6.0_17" class="java.beans.XMLDecoder">
<object class="javax.swing.JTree">
<object class="javax.swing.tree.DefaultTreeModel">
<object class="javax.swing.tree.DefaultMutableTreeNode">
<void property="userObject">
.. etc, but with none of my data in there.
(PS: Please be gentle, I'm very new to java!)
The XMLEncoder is a generic utility for encoding beans as text. I don't think it is suitable in your case.
I wrote a piece of code that does the job, assuming that I understand well your needs. You only have to pass the tree model as a parameter to the toXml method. Note that this is just a draft; You will probably want to handle exceptions differently, and manage your transformation parameters differently. More important, you can manipulate the recursive createTree method in order to change the structure of the XML node created per tree node.
public static String toXml(TreeModel model) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
// Build an XML document from the tree model
Document doc = impl.createDocument(null,null,null);
Element root = createTree(doc, model, model.getRoot());
doc.appendChild(root);
// Transform the document into a string
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
private static Element createTree(Document doc, TreeModel model, Object node) {
Element el = doc.createElement(node.toString());
for(int i=0;i<model.getChildCount(node);i++){
Object child = model.getChild(node, i);
el.appendChild(createTree(doc,model,child));
}
return el;
}
精彩评论