Newsgroup: it.comp.java
Titolo: Struttura ad albero da un file XML

Salve a tutti!
Devo scrivere un plug-in per Eclipse.
Alla fine, dopo certe elaborazioni, devo scrivere un file XML.
Sto cercando un qualcosa che mi crei una interfaccia grafica in modo
che possa visualizzare il contenuto del file XML come un albero,
alla maniera dell'albero sulla sinistra della finestra di "Esplora Risorse"
tanto per intenderci. Inoltre vorrei avere la possibilita' di colorare gli
elementi a seconda di certi valori.
Esiste una cosa del genere, o se no, come potrei indirizzare il mio lavoro??
Oppure, in alternativa, mi basterbbe anche un qualcosa che mi crei a partire
dal file XML delle pagine HTML che mi permettano di "navigare" attraverso
l'abero in questione!
Grazie a quanti vorranno aiutarmi!
--------------------------------
Inviato via 
http://arianna.libero.it/usenet/

ciao,
in rete si trova un esempio: io sono partito da quello,
e c'ho fatto poche modifiche per adattarlo alle mie esigneze:
il codice che uso e':
/*
 * XMLTree.java
 *
 * Created on June 23, 2006, 5:00 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package JnotiUI;
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
/** Given a filename or a name and an input stream,
 *  this class generates a JTree representing the
 *  XML structure contained in the file or stream.
 *  Parses with DOM then copies the tree structure
 *  (minus text and comment nodes).
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  
http://www.corewebprogramming.com/
.
 *  &copy; 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */
public class XMLTree extends JTree {
    public XMLTree(String filename) throws IOException {
        this(filename, new FileInputStream(new File(filename)));
    }
    public XMLTree(Document doc) {
        super(makeRootNode(doc));
    }
    public XMLTree(String filename, InputStream in) {
        super(makeRootNode(in));
    }
    // This method needs to be static so that it can be called
    // from the call to the parent constructor (super), which
    // occurs before the object is really built.
    private static DefaultMutableTreeNode
            makeRootNode(InputStream in) {
        try {
            // Use JAXP's DocumentBuilderFactory so that there
            // is no code here that is dependent on a particular
            // DOM parser. Use the system property
            // javax.xml.parsers.DocumentBuilderFactory (set either
            // from Java code or by using the -D option to "java").
            // or jre_dir/lib/jaxp.properties to specify this.
            DocumentBuilderFactory builderFactory =
                    DocumentBuilderFactory.newInstance();
            DocumentBuilder builder =
                    builderFactory.newDocumentBuilder();
            // Standard DOM code from hereon. The "parse"
            // method invokes the parser and returns a fully parsed
            // Document object. We'll then recursively descend the
            // tree and copy non-text nodes into JTree nodes.
            Document document = builder.parse(in);
            document.getDocumentElement().normalize();
            Element rootElement = document.getDocumentElement();
            DefaultMutableTreeNode rootTreeNode =
                    buildTree(rootElement);
            return(rootTreeNode);
        } catch(Exception e) {
            String errorMessage =
                    "Error making root node: " + e;
            System.err.println(errorMessage);
            e.printStackTrace();
            return(new DefaultMutableTreeNode(errorMessage));
        }
    }
    private static DefaultMutableTreeNode
            makeRootNode(Document document) {
        try {
            document.getDocumentElement().normalize();
            Element rootElement = document.getDocumentElement();
            DefaultMutableTreeNode rootTreeNode;
            //rootTreeNode.setCellRenderer(new MyRenderer());
            rootTreeNode = buildTree(rootElement);
            return(rootTreeNode);
        } catch(Exception e) {
            String errorMessage =
                    "Error making root node: " + e;
            System.err.println(errorMessage);
            e.printStackTrace();
            return(new DefaultMutableTreeNode(errorMessage));
        }
    }
    private static DefaultMutableTreeNode
            buildTree(Element rootElement) {
        // Make a JTree node for the root, then make JTree
        // nodes for each child and add them to the root node.
        // The addChildren method is recursive.
        DefaultMutableTreeNode rootTreeNode =
                new DefaultMutableTreeNode(treeNodeLabel(rootElement));
        addChildren(rootTreeNode, rootElement);
        return(rootTreeNode);
    }
    private static void addChildren
            (DefaultMutableTreeNode parentTreeNode,
            Node parentXMLElement) {
        // Recursive method that finds all the child elements
        // and adds them to the parent node. We have two types
        // of nodes here: the ones corresponding to the actual
        // XML structure and the entries of the graphical JTree.
        // The convention is that nodes corresponding to the
        // graphical JTree will have the word "tree" in the
        // variable name. Thus, "childElement" is the child XML
        // element whereas "childTreeNode" is the JTree element.
        // This method just copies the non-text and non-comment
        // nodes from the XML structure to the JTree structure.
        NodeList childElements =
                parentXMLElement.getChildNodes();
        for(int i=0; i<childElements.getLength(); i++) {
            Node childElement = childElements.item(i);
            if (!(childElement instanceof Text ||
                    childElement instanceof Comment)) {
                // simple text
                /*
                DefaultMutableTreeNode childTreeNode =
                        new DefaultMutableTreeNode
                        (treeNodeLabel(childElement));
                 */
                // simple text
                // elaborate text
                DefaultMutableTreeNode childTreeNode =
                        new DefaultMutableTreeNode
                        (treeNodeLabel(childElement));
                // elaborate text
                parentTreeNode.add(childTreeNode);
                addChildren(childTreeNode, childElement);
            }
        }
    }
    // If the XML element has no attributes, the JTree node
    // will just have the name of the XML element. If the
    // XML element has attributes, the names and values of the
    // attributes will be listed in parens after the XML
    // element name. For example:
    // XML Element: <blah>
    // JTree Node:  blah
    // XML Element: <blah foo="bar" baz="quux">
    // JTree Node:  blah (foo=bar, baz=quux)
    private static String treeNodeLabel(Node childElement) {
        NamedNodeMap elementAttributes =
                childElement.getAttributes();
        String treeNodeLabel = childElement.getNodeName();
        String redefineLabel = null;
        if (elementAttributes != null &&
                elementAttributes.getLength() > 0) {
            treeNodeLabel = treeNodeLabel + " (";
            int numAttributes = elementAttributes.getLength();
            for(int i=0; i<numAttributes; i++) {
                Node attribute = elementAttributes.item(i);
                if (i > 0) {
                    treeNodeLabel = treeNodeLabel + ", ";
                }
                treeNodeLabel =
                        treeNodeLabel + attribute.getNodeName() +
                        "=" + attribute.getNodeValue();
                if (attribute.getNodeName().equals("label"))
                    redefineLabel = attribute.getNodeValue();
            }
            treeNodeLabel = treeNodeLabel + ")";
        }
        if (redefineLabel != null)
            treeNodeLabel = redefineLabel;
        if (isSimpleTag(childElement)) {
            treeNodeLabel = treeNodeLabel + ": " +
getTextOfSimpleNode(childElement);
        }
        return treeNodeLabel;
    }
    static boolean isSimpleTag(Node n) {
        int count = (n.getChildNodes()).getLength();
        String nm = n.getNodeName();
        //System.out.print("isSimpleTag: Node: " + n.getNodeName() + "
- child count=" + count);
        if (count == 1 && nm != "#name") {
            //System.out.println(" returning TRUE");
            return true;
        } else {
            //System.out.println(" returning FALSE");
            return false;
        }
    }
    static String getTextOfSimpleNode(Node parent) {
        Node n = parent.getFirstChild();
        if (n == null)
            return "";
        if (n.getNodeType() != Node.TEXT_NODE)
            return "";
        // Must be a Plain text node
        Text textNode = (Text)n;
        String text = textNode.getData().trim();   // Strip off space
        if ((text == null) || text.length() <= 0)   // If empty
            return "";
        return text;
    }
}
Alessio Pelissi ha scritto:



...
Ti ringrazio 10000000000000000000! (<= non e' un punto esclamativo, e'
il simbolo del FATTORIALE!)
Alessio
