Question

Hi, I am trying to create an XML JTree viewer using the DOM parser instead of...

Hi, I am trying to create an XML JTree viewer using the DOM parser instead of the SAX parser, I am having trouble changing my code in order to utilize the DOM parser to extract the XML data into the tree structure. Would you be able to explain what changes should be made to the code in order to use the DOM parser instead of the SAX parser?

// Java Packages //     
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

// JTree model viewer //
public class XMLTreeViewer extends DefaultHandler {

private JTree xmlJTree;
DefaultTreeModel treeModel;
int lineCounter;

DefaultMutableTreeNode base = new DefaultMutableTreeNode("XML Viewer in Tree Structure");
static XMLTreeViewer treeViewer = null;
JTextField txtFile = null;

// Method to begin to using SAX Parser starting from base root branching out to child nodes //
@Override
public void startElement(String uri, String localName, String tagName, Attributes attr) throws SAXException {

DefaultMutableTreeNode current = new DefaultMutableTreeNode(tagName);

base.add(current);

base = current;

for (int i = 0; i < attr.getLength(); i++) {

DefaultMutableTreeNode currentAtt = new DefaultMutableTreeNode(attr.getLocalName(i) + " = "

+ attr.getValue(i));

base.add(currentAtt);
}

}

// error handling for entity parsing if not caught
public void skippedEntity(String name) throws SAXException {

System.out.println("Skipped Entity: '" + name + "'");
}

// Initial view of Jtree model idle //
@Override
public void startDocument() throws SAXException {

super.startDocument();
base = new DefaultMutableTreeNode("XML Viewer");

((DefaultTreeModel) xmlJTree.getModel()).setRoot(base);

}

// Adding Description to each subsequent child node //
public void characters(char[] ch, int start, int length) throws SAXException {

String s = new String(ch, start, length).trim();

if (!s.equals("")) {

DefaultMutableTreeNode current = new DefaultMutableTreeNode("Description : " + s);

base.add(current);

}

}

// End of current child node branching stopping at parent //
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {

base = (DefaultMutableTreeNode) base.getParent();

}

// Main Program Start //
public static void main(String[] args) {

treeViewer = new XMLTreeViewer();

// treeViewer.xmlSetUp();

treeViewer.createUI();

}

// Ends current XML file parsing and reloads //
@Override
public void endDocument() throws SAXException {

// Refresh JTree

((DefaultTreeModel) xmlJTree.getModel()).reload();

//Comment this out if you want the trees to be closed by default
//expandAll(xmlJTree);

}

// Expansion of Jtree structure levels //
public void expandAll(JTree tree) {

int row = 0;

while (row < tree.getRowCount()) {

tree.expandRow(row);

row++;
}

}

// Parser takes in current XML file to parse //
public void xmlSetUp(File xmlFile) {

try {

SAXParserFactory fact = SAXParserFactory.newInstance();

SAXParser parser = fact.newSAXParser();

parser.parse(xmlFile, this);

} catch (Exception e) {

}

}

// Jtree View component //
public void createUI() {

treeModel = new DefaultTreeModel(base);
xmlJTree = new JTree(treeModel);

JScrollPane scrollPane = new JScrollPane(xmlJTree);
JFrame windows = new JFrame();

windows.setTitle("XML file JTree Viewer using SAX Parser");

JPanel pnl = new JPanel();
pnl.setLayout(null);

JLabel lbl = new JLabel("File :");
txtFile = new JTextField("Selected File Name Here");

JButton btn = new JButton("Import File");
btn.addActionListener(new ActionListener() {

// JFile Chooser is opened after JButton interaction //
@Override
public void actionPerformed(ActionEvent evt) {

JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("xml files", "xml");

fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Open file");

if (ret == JFileChooser.APPROVE_OPTION) {

File file = fileopen.getSelectedFile();
txtFile.setText(file.getPath() + File.separator + file.getName());
xmlSetUp(file);

}

}

});

// Pane window size and interaction //
lbl.setBounds(0, 0, 100, 30);
txtFile.setBounds(110, 0, 250, 30);

btn.setBounds(360, 0, 100, 30);
scrollPane.setBounds(0, 50, 500, 600);

pnl.add(lbl);
pnl.add(txtFile);

pnl.add(btn);
pnl.add(scrollPane);

windows.add(pnl);
windows.setSize(500, 700);

windows.setVisible(true);
windows.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

   }

   }

Homework Answers

Answer #1

I have made changes in the code to parse the file using the DOM Parser. In xmlSetup() method I have made changes and commented it. You can uncomment the DOM code and comment your SAX Parser code. I have not tested the code with a XML doc. I hope this answer your questions.

Thanks.

------------------------------------------------------------------------------------------------------------------------------------------------------

// Java Packages //     

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.File;

import javax.swing.JButton;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextField;

import javax.swing.JTree;

import javax.swing.WindowConstants;

import javax.swing.filechooser.FileFilter;

import javax.swing.filechooser.FileNameExtensionFilter;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

/*-------CHANGES IN CODE FOR DOM PARSER--------

//Import following packages

import org.w3c.dom.*;

import javax.xml.parsers.*;

import java.io.*;

*/

// JTree model viewer //

public class XMLTreeViewer extends DefaultHandler {

private JTree xmlJTree;

DefaultTreeModel treeModel;

int lineCounter;

DefaultMutableTreeNode base = new DefaultMutableTreeNode("XML Viewer in Tree Structure");

static XMLTreeViewer treeViewer = null;

JTextField txtFile = null;

// Method to begin to using SAX Parser starting from base root branching out to child nodes //

@Override

public void startElement(String uri, String localName, String tagName, Attributes attr) throws SAXException

{

    DefaultMutableTreeNode current = new DefaultMutableTreeNode(tagName);

    base.add(current);

    base = current;

    for (int i = 0; i < attr.getLength(); i++) {

        DefaultMutableTreeNode currentAtt = new DefaultMutableTreeNode(attr.getLocalName(i) + " = "+ attr.getValue(i));

        base.add(currentAtt);

    }

}

// error handling for entity parsing if not caught

public void skippedEntity(String name) throws SAXException {

    System.out.println("Skipped Entity: '" + name + "'");

}

// Initial view of Jtree model idle //

@Override

public void startDocument() throws SAXException {

    super.startDocument();

    base = new DefaultMutableTreeNode("XML Viewer");

    ((DefaultTreeModel) xmlJTree.getModel()).setRoot(base);

}

// Adding Description to each subsequent child node //

public void characters(char[] ch, int start, int length) throws SAXException {

    String s = new String(ch, start, length).trim();

    if (!s.equals("")) {

        DefaultMutableTreeNode current = new DefaultMutableTreeNode("Description : " + s);

        base.add(current);

    }

}

// End of current child node branching stopping at parent //

public void endElement(String namespaceURI, String localName, String qName) throws SAXException {

    base = (DefaultMutableTreeNode) base.getParent();

}

// Main Program Start //

public static void main(String[] args) {

    treeViewer = new XMLTreeViewer();

    // treeViewer.xmlSetUp();

    treeViewer.createUI();

}

// Ends current XML file parsing and reloads //

@Override

public void endDocument() throws SAXException {

    // Refresh JTree

    ((DefaultTreeModel) xmlJTree.getModel()).reload();

    //Comment this out if you want the trees to be closed by defaul

    //expandAll(xmlJTree);

}

// Expansion of Jtree structure levels //

public void expandAll(JTree tree) {

    int row = 0;

    while (row < tree.getRowCount()) {

        tree.expandRow(row);

        row++;

    }

}

// Parser takes in current XML file to parse //

public void xmlSetUp(File xmlFile) {

    try {

        /*

        ---------- FOR DOM PARSER -------------

        //Get Document Builder

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();

        //Build Document

        Document document = builder.parse(new File( xmlFile ));

        //Normalize the XML Structure;

        document.getDocumentElement().normalize();

        //Here comes the root node

        Element root = document.getDocumentElement();

        */

        SAXParserFactory fact = SAXParserFactory.newInstance();

        SAXParser parser = fact.newSAXParser();

        parser.parse(xmlFile, this);

    } catch (Exception e) {

        }

    }

// Jtree View component //

public void createUI() {

    treeModel = new DefaultTreeModel(base);

    xmlJTree = new JTree(treeModel);

    JScrollPane scrollPane = new JScrollPane(xmlJTree);

    JFrame windows = new JFrame();

    windows.setTitle("XML file JTree Viewer using SAX Parser");

    JPanel pnl = new JPanel();

    pnl.setLayout(null);

    JLabel lbl = new JLabel("File :");

    txtFile = new JTextField("Selected File Name Here");

    JButton btn = new JButton("Import File");

    btn.addActionListener(new ActionListener() {

        // JFile Chooser is opened after JButton interaction //

        @Override

        public void actionPerformed(ActionEvent evt) {

            JFileChooser fileopen = new JFileChooser();

            FileFilter filter = new FileNameExtensionFilter("xml files", "xml");

            fileopen.addChoosableFileFilter(filter);

            int ret = fileopen.showDialog(null, "Open file");

            if (ret == JFileChooser.APPROVE_OPTION) {

                File file = fileopen.getSelectedFile();

                txtFile.setText(file.getPath() + File.separator + file.getName());

                xmlSetUp(file);

            }

        }

    });

    // Pane window size and interaction //

    lbl.setBounds(0, 0, 100, 30);

    txtFile.setBounds(110, 0, 250, 30);

    btn.setBounds(360, 0, 100, 30);

    scrollPane.setBounds(0, 50, 500, 600);

    pnl.add(lbl);

    pnl.add(txtFile);

    pnl.add(btn);

    pnl.add(scrollPane);

    windows.add(pnl);

    windows.setSize(500, 700);

    windows.setVisible(true);

    windows.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

}

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
I cannot for the life of me get this program to run properly. I don't know...
I cannot for the life of me get this program to run properly. I don't know what I'm doing wrong. Could the format of my text files be the issue? Edit: The program works this way, you choose a year and a gender and then enter a name. When you press the button its should give you the ranking or popularity of the name. There are 5 files that I have to search through, named 2006.txt to 2010.txt. First the...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the computer through a user interface. The user will choose to throw Rock, Paper or Scissors and the computer will randomly select between the two. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should then reveal the computer's choice and print a statement indicating if the user won, the computer won, or if it was a tie. Allow...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
Hi, I'm writing a Java program that prints a grid with circles and squares that have...
Hi, I'm writing a Java program that prints a grid with circles and squares that have letters in them and it is also supposed to print the toString() function to the console window each time the application runs. This toString() function is supposed to show the tile's shape, letter, and color component (or components). Could someone please review and debug my code to help me figure out why my toString() function is not working? import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton;...
package Week7_Quiz; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.Label;
package Week7_Quiz; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.stage.Stage; public class Week7_Quiz extends Application { private TextField tf1; private Label stckr; private int revrsdNum; private Button btn; int num = 0; int reverse; public static void main(String[] args) {       launch (args); } @Override public void start(Stage stage) throws Exception { tf1 = new TextField(); tf1.setLayoutX(10); tf1.setLayoutY(50);    stckr =new Label ("Result: "); stckr.setLayoutX(12); stckr.setLayoutY(100);    btn = new Button("Reverse");...
i am trying to wrire a word and change it to capital letters using client-server. im...
i am trying to wrire a word and change it to capital letters using client-server. im not able to write any words when i run the file in netbeans or command promot. is it something with my code? /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package assignment3retake; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter;...
Can you fix these errors in Android Studio? What I am trying to do is that...
Can you fix these errors in Android Studio? What I am trying to do is that developing an app to document the lifecycle of an “activity”. ------------------------------- AppDocumentationActivity.java: --------------------------------------- package com.example.activity_docmentation; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class AppDocumentationActivity extends AppCompatActivity { String message = getResources().getString(R.string.app_lifecycle_log); //Logcat tag String mActivityState; //refers to some state of activity int instanceTimes; //number of times instance is called String ACTIVITY_STATE_KEY; @Override...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Compile and execute the application. You will discover that is has a bug in it -...
Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn. Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code. Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the...