I am trying to do the following exercise:
Write a graphics program that allows a user to load an XML file from the disk using a file chooser GUI component. Once the file is open, its content is displayed in a java text area GUI component. A sample XML file can be found on moodle ‘Books.xml’.
It works but the xml document is not read correctly. The <> appear. See picture below :
1- This is my class ReadFilewithGui:
package Tut5Ex2Part1;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class ReadFileWithGui {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadFileWithGui window = new ReadFileWithGui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ReadFileWithGui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JTextArea textArea = new JTextArea();
textArea.setBounds(56, 73, 346, 100);
frame.getContentPane().add(textArea);
JButton btnGetFile = new JButton("Get file");
btnGetFile.setFont(new Font("Lantinghei TC", Font.PLAIN, 13));
btnGetFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
OpenFile of= new OpenFile();
try{
of.PickMe();
}
catch (Exception e){
e.printStackTrace();
}
textArea.setText(of.sb.toString());
}
});
btnGetFile.setBounds(175, 219, 117, 29);
frame.getContentPane().add(btnGetFile);
}
This is my OpenFileClass:
package Tut5Ex2Part1;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class OpenFile{
JFileChooser fileChooser = new JFileChooser();
StringBuilder sb = new StringBuilder();
//String builder is not inmutable
public void PickMe() throws Exception{
//Opens open file dialog
if(fileChooser.showOpenDialog(null)== JFileChooser.APPROVE_OPTION) {
//returns selected file. We are using the GUI file chooser
java.io.File file = fileChooser.getSelectedFile();
//creates a scanner for the file
Scanner input = new Scanner(file);
while(input.hasNext()){
sb.append(input.nextLine());
sb.append("\n");
}
//closes scanner when we are finished
input.close();
}
else{
//if file not selected. example cancel botton.
sb.append("You have not selected a file");
}
}
}
This is my XML file
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
</catalog>
Any help is welcome! Thanks :)