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
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 =...
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 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...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Question: I am using three different ways to execute this program. I am a bit confused...
Question: I am using three different ways to execute this program. I am a bit confused on the time complexity for each one. Can someone explain the time complexity for each function in relation to the nanoseconds. import java.util.HashMap; import java.util.Map; public class twosums {       public static void main(String args[]) {               int[] numbers = new int[] {2,3,9,4,8};;        int target = 10;               long nano_begin1 = System.nanoTime();        int[]...
Here is my java code, I keep getting this error and I do not know how...
Here is my java code, I keep getting this error and I do not know how to fix it: PigLatin.java:3: error: class Main is public, should be declared in a file named Main.java public class Main { ^ import java.io.*; public class Main { private static BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String english = getString(); String translated = translate(english); System.out.println(translated); } private static String translate(String s) { String latin =...
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...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...