[Java] XML2JTree →→→→→进入此内容的聊天室

来自 , 2021-02-24, 写在 Java, 查看 146 次.
URL http://www.code666.cn/view/f670ef5d
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package yan.t1;
  7.  
  8. // Import the W3C DOM clas ses
  9. import org.w3c.dom.*;
  10.  
  11. // We are going to use JAXP's classes for DOM I/O
  12. import javax.xml.parsers.*;
  13.  
  14. // Import other Java classes
  15. import javax.swing.*;
  16. import javax.swing.tree.*;
  17. import java.awt.*;
  18. import java.awt.event.*;
  19. import java.io.*;
  20.  
  21. /**
  22.  * Displays XML in a JTree
  23.  */
  24. public class XML2JTree extends JPanel {
  25.  
  26.     private JTree jTree;
  27.     private static JFrame frame;
  28.  
  29.     public static final int FRAME_WIDTH = 440;
  30.     public static final int FRAME_HEIGHT = 280;
  31.  
  32.     public XML2JTree(Node root, boolean showDetails) {
  33.         // Take a DOM and convert it to a Tree model for the JTree
  34.         DefaultMutableTreeNode top = createTreeNode(root, showDetails);
  35.         DefaultTreeModel dtModel = new DefaultTreeModel(top);
  36.  
  37.         // Create our JTree
  38.         jTree = new JTree(dtModel);
  39.  
  40.         // We have no tree listener but this looks more natrual
  41.         jTree.getSelectionModel().setSelectionMode(
  42.                 TreeSelectionModel.SINGLE_TREE_SELECTION);
  43.         jTree.setShowsRootHandles(true);
  44.  
  45.         // If this were editable it would result in too much code
  46.         // for this demo.
  47.         jTree.setEditable(false);
  48.  
  49.         // Create a new JScrollPane but override one of the methods.
  50.         JScrollPane jScroll = new JScrollPane() {
  51.             // This keeps the scrollpane a reasonable size
  52.             public Dimension getPreferredSize() {
  53.                 return new Dimension(FRAME_WIDTH - 20, FRAME_HEIGHT - 40);
  54.             }
  55.         };
  56.  
  57.         // Wrap the JTree in a JScroll so that we can scroll it in the JSplitPane.
  58.         jScroll.getViewport().add(jTree);
  59.  
  60.         JPanel panel = new JPanel();
  61.         panel.setLayout(new BorderLayout());
  62.         panel.add("Center", jScroll);
  63.         add("Center", panel);
  64.     }
  65.  
  66.     /**
  67.      *
  68.      * This takes a DOM Node and recurses through the children until each one is
  69.      * added to a DefaultMutableTreeNode. This can then be used by the JTree as
  70.      * a tree model. The second parameter can be used to provide more visual
  71.      * detail for debugging.
  72.      *
  73.      */
  74.     protected DefaultMutableTreeNode createTreeNode(Node root, boolean showDetails) {
  75.         DefaultMutableTreeNode dmtNode = null;
  76.  
  77.         String type = getNodeType(root);
  78.         String name = root.getNodeName();
  79.         String value = root.getNodeValue();
  80.  
  81.         if (showDetails) {
  82.             dmtNode = new DefaultMutableTreeNode("[" + type + "] --> " + name + " = " + value);
  83.         } else {
  84.             // Special case for TEXT_NODE, others are similar but not catered for here.
  85.             dmtNode = new DefaultMutableTreeNode(
  86.                     root.getNodeType() == Node.TEXT_NODE ? value : name);
  87.         }
  88.  
  89.         // Display the attributes if there are any
  90.         NamedNodeMap attribs = root.getAttributes();
  91.         if (attribs != null && showDetails) {
  92.             for (int i = 0; i < attribs.getLength(); i++) {
  93.                 Node attNode = attribs.item(i);
  94.                 String attName = attNode.getNodeName().trim();
  95.                 String attValue = attNode.getNodeValue().trim();
  96.  
  97.                 if (attValue != null) {
  98.                     if (attValue.length() > 0) {
  99.                         dmtNode.add(new DefaultMutableTreeNode(
  100.                                 "[Attribute] --> " + attName + "=\"" + attValue + "\""));
  101.                     }
  102.                 }
  103.             }
  104.         }
  105.  
  106.         // If there are any children and they are non-null then recurse...
  107.         if (root.hasChildNodes()) {
  108.             NodeList childNodes = root.getChildNodes();
  109.             if (childNodes != null) {
  110.                 for (int k = 0; k < childNodes.getLength(); k++) {
  111.                     Node nd = childNodes.item(k);
  112.                     if (nd != null) {
  113.                         // A special case could be made for each Node type.
  114.                         if (nd.getNodeType() == Node.ELEMENT_NODE) {
  115.                             dmtNode.add(createTreeNode(nd, showDetails));
  116.                         }
  117.  
  118.                         // This is the default
  119.                         String data = nd.getNodeValue();
  120.                         if (data != null) {
  121.                             data = data.trim();
  122.                             if (!data.equals("\n") && !data.equals("\r\n")
  123.                                     && data.length() > 0) {
  124.                                 dmtNode.add(createTreeNode(nd, showDetails));
  125.                             }
  126.                         }
  127.                     }
  128.                 }
  129.             }
  130.         }
  131.         return dmtNode;
  132.     }
  133.  
  134.     /**
  135.      *
  136.      * This simple method returns a displayable string given a NodeType
  137.      *
  138.      */
  139.     public String getNodeType(Node node) {
  140.         String type;
  141.  
  142.         switch (node.getNodeType()) {
  143.             case Node.ELEMENT_NODE: {
  144.                 type = "Element";
  145.                 break;
  146.             }
  147.             case Node.ATTRIBUTE_NODE: {
  148.                 type = "Attribute";
  149.                 break;
  150.             }
  151.             case Node.TEXT_NODE: {
  152.                 type = "Text";
  153.                 break;
  154.             }
  155.             case Node.CDATA_SECTION_NODE: {
  156.                 type = "CData section";
  157.                 break;
  158.             }
  159.             case Node.ENTITY_REFERENCE_NODE: {
  160.                 type = "Entity reference";
  161.                 break;
  162.             }
  163.             case Node.ENTITY_NODE: {
  164.                 type = "Entity";
  165.                 break;
  166.             }
  167.             case Node.PROCESSING_INSTRUCTION_NODE: {
  168.                 type = "Processing instruction";
  169.                 break;
  170.             }
  171.             case Node.COMMENT_NODE: {
  172.                 type = "Comment";
  173.                 break;
  174.             }
  175.             case Node.DOCUMENT_NODE: {
  176.                 type = "Document";
  177.                 break;
  178.             }
  179.             case Node.DOCUMENT_TYPE_NODE: {
  180.                 type = "Document type";
  181.                 break;
  182.             }
  183.             case Node.DOCUMENT_FRAGMENT_NODE: {
  184.                 type = "Document fragment";
  185.                 break;
  186.             }
  187.             case Node.NOTATION_NODE: {
  188.                 type = "Notation";
  189.                 break;
  190.             }
  191.             default: {
  192.                 type = "Unknown, contact Sun!";
  193.                 break;
  194.             }
  195.         }
  196.         return type;
  197.     }
  198.  
  199.     /**
  200.      *
  201.      * A common point of exit...
  202.      *
  203.      */
  204.     private static void exit() {
  205.         System.out.println("Graceful exit");
  206.         System.exit(0);
  207.     }
  208.  
  209.     /**
  210.      *
  211.      * This main is simply to test this class
  212.      *
  213.      */
  214.     public static void main(String[] args) {
  215.         Document doc = null;
  216.  
  217.         // Just check we have the right parameters first.
  218.         if (args.length < 1) {
  219.             System.out.println("Usage:\tXML2JTree filename.xml");
  220.             return;
  221.         }
  222.         String filename = args[0];
  223.  
  224.         boolean showDetails = false;
  225.         if (args.length == 2) {
  226.             // If anything's there override the default
  227.             showDetails = Boolean.valueOf(args[1]).booleanValue();
  228.         }
  229.  
  230.         // Create a frame to "hold" our class
  231.         frame = new JFrame("XML to JTree");
  232.  
  233.         Toolkit toolkit = Toolkit.getDefaultToolkit();
  234.         Dimension dim = toolkit.getScreenSize();
  235.         int screenHeight = dim.height;
  236.         int screenWidth = dim.width;
  237.  
  238.         // This should display a WIDTH x HEIGHT sized Frame in the middle of the screen
  239.         frame.setBounds((screenWidth - FRAME_WIDTH) / 2,
  240.                 (screenHeight - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
  241.  
  242.         frame.setBackground(Color.lightGray);
  243.         frame.getContentPane().setLayout(new BorderLayout());
  244.  
  245.         // Give our frame an icon when it's minimized.
  246.         frame.setIconImage(toolkit.getImage("Wrox.gif"));
  247.  
  248.         // Add a WindowListener so that we can close the window
  249.         WindowListener wndCloser = new WindowAdapter() {
  250.             public void windowClosing(WindowEvent e) {
  251.                 exit();
  252.             }
  253.         };
  254.         frame.addWindowListener(wndCloser);
  255.  
  256.         try {
  257.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  258.             dbf.setValidating(false);  // Not important fro this demo
  259.  
  260.             DocumentBuilder db = dbf.newDocumentBuilder();
  261.             doc = db.parse(filename);
  262.         } catch (FileNotFoundException fnfEx) {
  263.             // Display a "nice" warning message if the file isn't there.
  264.             JOptionPane.showMessageDialog(frame, filename + " was not found",
  265.                     "Warning", JOptionPane.WARNING_MESSAGE);
  266.  
  267.             System.out.println();
  268.             exit();
  269.         } catch (Exception ex) {
  270.             JOptionPane.showMessageDialog(frame, ex.getMessage(), "Exception",
  271.                     JOptionPane.WARNING_MESSAGE);
  272.  
  273.             ex.printStackTrace();
  274.             exit();
  275.         }
  276.  
  277.         Node root = (Node) doc.getDocumentElement();
  278.  
  279.         frame.getContentPane().add(new XML2JTree(root, showDetails),
  280.                 BorderLayout.CENTER);
  281.  
  282.         frame.validate();
  283.         frame.setVisible(true);
  284.     }
  285. }
  286.  

回复 "XML2JTree"

这儿你可以回复上面这条便签

captcha