An XSLT Editor Tool - Part I The Basic GUI and Opening and Displaying an XML File

April 25, 2002 -- Part I The Basic GUI and Opening and displaying an XML File. The following tutorial describes the development of a simple application to edit and transform XML using XSLT. It also illustrates how the system clipboard may be accessed to cut and paste text between windows on your desktop and use of undo and redo within an editor pane. It doesn't provide text highlighting or an outline view of a document. The editor is easy to use and ideal for those situations where you want to make a simple change and observe the results.

The GUI that is going to be developed consists of tabbed panes to show the XML file, the XSLT file, the transformed output, and an output log. The GUI is shown in Figure 1. The toolbar provides functionality for opening/saving files and URLs, cut, paste, undo, and redo.


Figure 1. The XSLT Editor GUI

This GUI was developed using Sun Microsystems' Forte Community Edition IDE. The Swing application template provided by the IDE provided the basic GUI. Additional elements were added to the toolbar by dragging them from the component palette. An action event handler was then created for each toolbar item. One of the functions to be performed is to read an XML file from the local file system. An event handler is created for this using the Component Inspector (See Figure 2).

Figure 2. Create event handler for open xml file on the menu bar

The openXmlMenuItemAction primary function is to display a file chooser to let the user select an XML file from the local file system and then display it in the XML editor pane. It checks if the user has already opened a file and made changes. If they have, a dialog is displayed asking whether or not they want to save changes. To make the tool easier to use, the previously used directory is set as the default. The following code listing for the method "openXmlFileMenuActionPerformed" illustrates how these functions can be provided.

/**
     * Create dialog for selecting an XML file and then display the contents in
     * an editor pane
     * @param evt ActionEvent 
     */
    private void openXmlFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        // First check if xml document has been changed, and ask if user wants 
        // to save it
        if (xmlUndo.canUndo()) {
            int result=JOptionPane.showConfirmDialog(this,
               "XML document has been modified, do you wish to save the changes to a local file?",
               "Save Changes",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
            if (result==0) {
                saveXmlMenuItemActionPerformed(null);
            }
        }
        
        // Create file chooser dialog
        JFileChooser chooser = new JFileChooser();
        
        // Create filter so only xml files are shown in file chooser
        ExtensionFileFilter filter = new ExtensionFileFilter();
        filter.setExtension(".xml");
        filter.setDescription("XML Files");
        chooser.setFileFilter(filter);
        
        // Set default directory to that previously used when xml or xslt file opened
        if (lastXmlDir!=null) {
            chooser.setCurrentDirectory(lastXmlDir);
        }
        else {
            if (lastXsltDir!=null) {
                chooser.setCurrentDirectory(lastXsltDir);
            }
        }
        
        // Display the file chooser dialog
        int returnVal = chooser.showOpenDialog(this);
        
        // Open the selected file
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            log("Opened XML file: " +chooser.getSelectedFile().getName());
            
            // open the selected xml file
            File xmlFile = chooser.getSelectedFile();
            
            try {
                xmlEditorPane.setText("");
                
                // Parse the xml file
                inputDoc=documentBuilder.parse(xmlFile);
                
				// Convert the xml document to string for display
                try {
                    xmlEditorPane.setText(documentToString(inputDoc));
                }
                catch (TransformerException e){
                    log(e.getMessage());
                    tabbedPane.setSelectedIndex(3);
                }

                xmlUndo.discardAllEdits();
                tabbedPane.setSelectedIndex(0);
 
                // Remember what directory we're in for next time
                String xmlFileName=xmlFile.getAbsolutePath();
                int j=xmlFileName.lastIndexOf(File.separator);
                String dir=xmlFile.getAbsolutePath().substring(0,j);
                lastXmlDir=new File(dir);                
                saveProps();
            }
            catch (IOException e) {
                log(e.getMessage());
                tabbedPane.setSelectedIndex(3);
            }
            catch (org.xml.sax.SAXException e) {
                log(e.getMessage());
                tabbedPane.setSelectedIndex(3);
            }
            
            
        }
        
    }
   

The method documentToString referenced in the above method converts the XML document to string that may be displayed in the JEditPane. The document is transformed and output is sent to a StringWriter. The StringWriter's "toString" method then returns contents of the document as a string.

     /**
     * Convert document to string for display
     * @param doc org.w3c.dom.Document
	 * @return String
     */
    private String documentToString(org.w3c.dom.Document doc) throws TransformerException {
        
        // Create dom source for the document
        DOMSource domSource=new DOMSource(doc);
        
        // Create a string writer
        StringWriter stringWriter=new StringWriter();
        
        // Create the result stream for the transform
        StreamResult result = new StreamResult(stringWriter);
        
        // Create a Transformer to serialize the document
        TransformerFactory tFactory =TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty("indent","yes");
        
        // Transform the document to the result stream
        transformer.transform(domSource, result);        
        return stringWriter.toString();
    }

Back to Article Index Next, XSLT Transformations