How to implement conversion between XML documents and JTree

Source: Internet
Author: User
Tags format definition
XML is widely used in document format definition due to its good structure. We know that application software usually needs to use configuration files to determine some runtime parameters. The configuration file of the previous application is generally a. ini file. Although the INI file is still in use, due to the emergence of XML, more and more commercial software is using XML as the configuration file format, such as BEA Weblogic and IBM Websphere. Therefore, when designing a software configuration file, we will increasingly consider using XML for... XML because of its good structure, which is widely used in document format definition. We know that application software usually needs to use configuration files to determine some runtime parameters. The configuration file of the previous application is generally a. ini file. Although the INI file is still in use, due to the emergence of XML, more and more commercial software is using XML as the configuration file format, such as BEA Weblogic and IBM Websphere. Therefore, when designing a software configuration file, we will increasingly consider using XML as the format of the configuration file.

Because the configuration file sometimes must be modified by users, providing a visual format for editing the configuration file is a good embodiment of user interaction of the software. We must find a visual method for the XML document. JTree in the Swing component in the Java language is suitable for the visualization of XML documents. There is a convenient conversion method between the two. This means that we can easily modify the user's operations on the JTree after saving the disk, as well as present the XML file to the user easily as a JTree.

Visualization of XML documents

An XML document is actually a tree structure. For example, the following XML document:

 
   
      
   
    
Classical
       
   
    
D: \ software \ App \ skin
       Head1.bmp    
   
    
Center1.bmp
       
   
    
Foot1.bmp
     
  
      
   
    
Modern
       
   
    
D: \ software \ App \ skin
       Head2.bmp    
   
    
Center2.bmp
       
   
    
Foot2.bmp
     
  
 

As you can see, this XML document is a multi-Interface Program interface image configuration program. If you visualize this XML document, you should get the result shown in using JTree.

Then design an XMLTree class that inherits the definition and member variables of the JTree class. the Function definition is as follows:

Public class XMLTree extends JTree {private DefaultMutableTreeNode treeNode; // The root node of JTree, private DocumentBuilderFactory dbf; // these three member variables are the private DocumentBuilder db required by xml parser; private Document doc; XMLTree (String fileName); // Constructor for initialization public DefaultMutableTreeNode LoadFile (Node root); // generate the public void SaveToFile (DefaultMutableTreeNode root, fileWriter fw); // save the tree into an XML file private Node parseXml (String text )}

The initialization work of the constructor is as follows:

XMLTree (String fileName) {dbf = DocumentBuilderFactory. newInstance (); // Generate dbf instance db = dbf. newDocumentBuilder (); // Generate the database instance treeNode = LoadFile (getXMLRoot (text); // Parse the xml file, return the JTree root node setModel (new DefaultTreeModel (treeNode); // Generate a JTree based on the root node}

ParseXml is a program that returns the root element of the XML file, as follows:

Private Node getXMLRoot (String text) {ByteArrayInputStream byteStream; byteStream = new ByteArrayInputStream (text. getBytes (); // read the XML file to the Stream to try {doc = db. parse (byteStream); // parse the xml file. } Catch (Exception e) {e. printStackTrace ();} return (Node) doc. getDocumentElement (); // return the root element of the DOM tree of the XML file}

The core part of LoadFile is a recursive process, as follows:

Private DefaultMutableTreeNode createTreeNode (Node root) {DefaultMutableTreeNode treeNode = null; // defines the root Node String name = root to be returned. getNodeName (); // Obtain the node's NodeName String value = root. getNodeValue (); // Obtain the node's NodeValue treeNode = new DefaultMutableTreeNode (root. getNodeType () = Node. TEXT_NODE? Value: name); // if it is a value node, the value of the node is obtained. Otherwise, the name of the node Tag is obtained if (root. hasChildNodes () // if the node has a child node, recursively process the child node {NodeList children = root. getChildNodes (); // Obtain the subnode list of the node if (children! = Null) {// determines whether the child node is null int numChildren = children. getLength (); // get the number of bytes for (int I = 0; I <numChildren; I ++) {Node node = children. item (I); // process each subnode cyclically if (node! = Null) {if (node. getNodeType () = Node. ELEMENT_NODE) {treeNode. add (createTreeNode (node); // if the child node has a child node, use recursive method to process the child node} else {String data = node. getNodeValue (); if (data! = Null) {data = data. trim (); if (! Data. equals ("\ n ")&&! Data. equals ("\ r \ n") & data. length ()> 0) {treeNode. add (new DefaultMutableTreeNode (node. getNodeValue (); // if the node does not have a child node, directly add it to the node }}}} return treeNode; // return node}

The methods in the Java Swing package can be easily modified on the JTree. you can use the pop-up dialog box method or directly modify the JTree. After the JTree is changed, it is a recursive process to write a JTree into an XML file. the method is as follows:

Public void SaveToFile (DefaultMutableTreeNode, FileWriter fw) {try {if (root. isLeaf () fw. write (root. toString () + "\ r \ n "); // if it is a leaf node, the node is directly output to the file else {// if it is not a leaf node, the node fw is recursively output. write ("<" + root. toString () + "> \ r \ n"); for (int I = 0; I <root. getChildCount (); I ++) {DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) root. getChildAt (I); saveFile (childNode, fw); // recursively output all child nodes of the node} fw. write ("
 \ R \ n ") ;}} catch (Exception e) {e. printStackTrace ();}}

Note that if the XML file contains Chinese characters, you must enter the encoding method of the XML file in the file before calling the above function. the method is as follows:

fw.write(“
 \r\n”);

After the function is called, close the file:

fw.close()
Conclusion

XML files are widely used in configuration files and information transmission. There are many visualization methods. This article introduces one of the implementation methods by combining Java's JTree class. The good combination of Java and XML makes it flexible and convenient to compile XML programs using Java.

The preceding section describes how to implement the conversion between the XML document and the JTree. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.