将JTree转换为XML

时间:2010-04-06 20:27:09

标签: java xml jtree

我见过很多关于如何将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的新手!)

1 个答案:

答案 0 :(得分:1)

XMLEncoder是一个将bean编码为文本的通用实用程序。我不认为它适合你的情况。

我写了一段代码来完成这项工作,假设我很了解你的需求。您只需将树模型作为参数传递给toXml方法。请注意,这只是草稿;您可能希望以不同方式处理异常,并以不同方式管理转换参数。更重要的是,您可以操作递归createTree方法,以便更改每个树节点创建的XML节点的结构。

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;
}