将 JTree 转换为 XML
我看过很多关于如何将 XML 读入 JTree 的文章,但很少有关于如何从 JTree 创建 XML 的文章。谁能帮我用一个简单的方法来解决这个问题?我见过一个看起来像这样的例子:
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream(f.toString())));
e.writeObject(o);
e.close();
.. 但我无法让它工作;它返回一个 XML 文件,但不太正确,如下所示:
<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">
.. 等,但其中没有我的数据。
(PS:请温柔点,我对 Java 非常陌生!)
I've seen many many articles on how to read XML into a JTree but few on how to create 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!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XMLEncoder 是用于将 bean 编码为文本的通用实用程序。我认为它不适合你的情况。
我编写了一段代码来完成这项工作,假设我很了解您的需求。您只需将树模型作为参数传递给 toXml 方法。请注意,这只是一个草案;您可能希望以不同的方式处理异常,并以不同的方式管理转换参数。更重要的是,您可以操作递归 createTree 方法来更改每个树节点创建的 XML 节点的结构。
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.