javaxmlswingjtreetreemodel

Converting JTree to Xml in java


I am working on JTree and i need to Create XML file of Jtree so is there any good way to convert it? I am using JTree in java. I just need to convert it and i have Checkbox as node into the Tree and i have used render for it. and when submit call i need to convert that Jtree into XML. is there any good way for that??

My Tree is Dynamically Created. so i need to convert it.

i tried this

try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            Document doc = factory.newDocumentBuilder().newDocument();
            Element rootElement = doc.createElement("Vervesystems");

            TreeNode root = (TreeNode) jTree1.getModel().getRoot();

            parseTreeNode(root, rootElement);
            System.out.println("Node name"+root.toString());
            System.err.println("Root node"+root.getChildCount());

            Transformer tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty(OutputKeys.METHOD, "xml");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            DOMSource domSource = new DOMSource(doc);
            StreamResult sr = new StreamResult(new File("/home/kishan/NetBeansProjects/03-02-2014-VISDashboard/src/com/verve/visdashboard/TreeModel.xml"));
            tf.transform(domSource, sr);


        } catch (Exception e) {
            System.err.println("This is exception "+e);

        }

private void parseTreeNode(TreeNode treeNode, Node doc) {
        try {
        Element parentElement = doc.getOwnerDocument().createElement("folder");
        doc.appendChild(parentElement);

        System.err.println("Element name"+parentElement.getTagName());

        // Apply properties to root element...
        org.w3c.dom.Attr attrName = doc.getOwnerDocument().createAttribute("DisplayName");
        attrName.setNodeValue("Treenode");
        System.err.println("Count"+treeNode.getChildCount());
        parentElement.getAttributes().setNamedItem(attrName);


        Enumeration kiddies = treeNode.children();

        while (kiddies.hasMoreElements()) {
            TreeNode child = (TreeNode) kiddies.nextElement();
            //doc.appendChild(child);
            System.out.println("Child"+child.toString());
            parseTreeNode(child, parentElement);
        }

        } catch (Exception e) {
            System.err.println("exception is here"+e);
        }

but its Wrting blank only in myxml file. can anybody give suggestion. Example image is here. enter image description here


Solution

  • The basic concept is simple. A TreeModel is just a bunch of linked nodes, which may or may not contain children

    Creating the XML is a "little" more complex, but not that difficult, in fact, the most difficult part would be trying to parse each node and saving it...

    Take a look at Java API for XML Processing (JAXP) for more details

    import java.io.File;
    import java.util.Enumeration;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    
    public class ConvertToXML {
    
        public static void main(String[] args) {
            TreeModel model = new DefaultTreeModel(...);
    
            try {
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                Document doc = factory.newDocumentBuilder().newDocument();
                Element rootElement = doc.createElement("treeModel");
    
                doc.appendChild(rootElement);
    
                // Get tree root...
                TreeNode root = (TreeNode) model.getRoot();
    
                parseTreeNode(root, rootElement);
    
                // Save the document to disk...
    
                Transformer tf = TransformerFactory.newInstance().newTransformer();
                tf.setOutputProperty(OutputKeys.INDENT, "yes");
                tf.setOutputProperty(OutputKeys.METHOD, "xml");
                tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
                DOMSource domSource = new DOMSource(doc);
                StreamResult sr = new StreamResult(new File("TreeModel.xml"));
                tf.transform(domSource, sr);
    
            } catch (ParserConfigurationException | TransformerException ex) {
                ex.printStackTrace();
            }
        }
    
        private static void parseTreeNode(TreeNode treeNode, Node doc) {
    
            Element parentElement = doc.getOwnerDocument().createElement("node");
            doc.appendChild(parentElement);
    
            // Apply properties to root element...
            Attr attrName = doc.getOwnerDocument().createAttribute("name");
            attrName.setNodeValue(...);
            parentElement.getAttributes().setNamedItem(attrName);
    
            Enumeration kiddies = treeNode.children();
            while (kiddies.hasMoreElements()) {
                TreeNode child = (TreeNode) kiddies.nextElement();
                parseTreeNode(child, parentElement);
            }
    
        }
    
    }
    

    Updated with runnable example

    The following example is based on the examples from How to use Trees

    And produces the following output...

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Library>
        <catagory name="Books for Java Programmers">
            <book name="The Java Tutorial: A Short Course on the Basics" url="tutorial.html"/>
            <book name="The Java Tutorial Continued: The Rest of the JDK" url="tutorialcont.html"/>
            <book name="The JFC Swing Tutorial: A Guide to Constructing GUIs" url="swingtutorial.html"/>
            <book name="Effective Java Programming Language Guide" url="bloch.html"/>
            <book name="The Java Programming Language" url="arnold.html"/>
            <book name="The Java Developers Almanac" url="chan.html"/>
        </catagory>
        <catagory name="Books for Java Implementers">
            <book name="The Java Virtual Machine Specification" url="vm.html"/>
            <book name="The Java Language Specification" url="jls.html"/>
        </catagory>
    </Library>
    

    The code...

    import java.io.File;
    import java.util.Enumeration;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    
    public class TreeExample {
    
        public static void main(String[] args) {
            DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
            createNodes(top);
            TreeModel model = new DefaultTreeModel(top);
    
            try {
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                Document doc = factory.newDocumentBuilder().newDocument();
    
                // Get tree root...
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    
                parseTreeNode(root, doc);
    
                // Save the document to disk...
                Transformer tf = TransformerFactory.newInstance().newTransformer();
                tf.setOutputProperty(OutputKeys.INDENT, "yes");
                tf.setOutputProperty(OutputKeys.METHOD, "xml");
                tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
                DOMSource domSource = new DOMSource(doc);
                StreamResult sr = new StreamResult(new File("TreeModel.xml"));
                tf.transform(domSource, sr);
    
            } catch (ParserConfigurationException | TransformerException ex) {
                ex.printStackTrace();
            }
        }
    
        protected static void parseTreeNode(DefaultMutableTreeNode treeNode, Document doc) {
    
                String value = treeNode.getUserObject().toString();
                Element rootElement = doc.createElement("Library");
                doc.appendChild(rootElement);
    
                Enumeration kiddies = treeNode.children();
                while (kiddies.hasMoreElements()) {
                    DefaultMutableTreeNode child = (DefaultMutableTreeNode) kiddies.nextElement();
                    parseTreeNode(child, rootElement);
                }
    
        }
    
        protected static void parseTreeNode(DefaultMutableTreeNode treeNode, Element doc) {
    
            Object value = treeNode.getUserObject();
    
            Element parentElement = null;
            if (value instanceof BookInfo) {
                parentElement = doc.getOwnerDocument().createElement("book");
    
                BookInfo book = (BookInfo) value;
                // Apply properties to root element...
                Attr attrName = doc.getOwnerDocument().createAttribute("name");
                attrName.setNodeValue(book.getBookName());
                parentElement.getAttributes().setNamedItem(attrName);
    
                Attr attrURL = doc.getOwnerDocument().createAttribute("url");
                attrURL.setNodeValue(book.getBookURL());
                parentElement.getAttributes().setNamedItem(attrURL);
            } else if (value instanceof BookCatagory) {
                parentElement = doc.getOwnerDocument().createElement("catagory");
    
                BookCatagory book = (BookCatagory) value;
                // Apply properties to root element...
                Attr attrName = doc.getOwnerDocument().createAttribute("name");
                attrName.setNodeValue(book.getCatagory());
                parentElement.getAttributes().setNamedItem(attrName);
            }
    
            doc.appendChild(parentElement);
    
            Enumeration kiddies = treeNode.children();
            while (kiddies.hasMoreElements()) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) kiddies.nextElement();
                parseTreeNode(child, parentElement);
            }
        }
    
        protected static void createNodes(DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
    
            category = new DefaultMutableTreeNode(new BookCatagory("Books for Java Programmers"));
            top.add(category);
    
            //original Tutorial
            book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial: A Short Course on the Basics",
                    "tutorial.html"));
            category.add(book);
    
            //Tutorial Continued
            book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial Continued: The Rest of the JDK",
                    "tutorialcont.html"));
            category.add(book);
    
            //JFC Swing Tutorial
            book = new DefaultMutableTreeNode(new BookInfo("The JFC Swing Tutorial: A Guide to Constructing GUIs",
                    "swingtutorial.html"));
            category.add(book);
    
            //Bloch
            book = new DefaultMutableTreeNode(new BookInfo("Effective Java Programming Language Guide",
                    "bloch.html"));
            category.add(book);
    
            //Arnold/Gosling
            book = new DefaultMutableTreeNode(new BookInfo("The Java Programming Language", "arnold.html"));
            category.add(book);
    
            //Chan
            book = new DefaultMutableTreeNode(new BookInfo("The Java Developers Almanac",
                    "chan.html"));
            category.add(book);
    
            category = new DefaultMutableTreeNode(new BookCatagory("Books for Java Implementers"));
            top.add(category);
    
            //VM
            book = new DefaultMutableTreeNode(new BookInfo("The Java Virtual Machine Specification",
                    "vm.html"));
            category.add(book);
    
            //Language Spec
            book = new DefaultMutableTreeNode(new BookInfo("The Java Language Specification",
                    "jls.html"));
            category.add(book);
        }
    
        public static class BookCatagory {
    
            private String catagory;
    
            public BookCatagory(String cat) {
                this.catagory = cat;
            }
    
            public String getCatagory() {
                return catagory;
            }
    
        }
    
        private static class BookInfo {
    
            private String bookName;
            private String bookURL;
    
            public BookInfo(String book, String filename) {
                bookName = book;
                bookURL = filename;
            }
    
            public String getBookName() {
                return bookName;
            }
    
            public String getBookURL() {
                return bookURL;
            }
    
            public String toString() {
                return bookName;
            }
        }
    }