I have the following code to parse a file, I know the parsing works as I had hard coded in a path to a file. I am now trying to give the user the option of picking a file to parse. I am having trouble editing the code to use the JFileChooser:
import java.util.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class XMLReader
{
public static void main(String argv[]) {
// create a file chooser
JFileChooser fileChooser = new JFileChooser();
// show open file dialog
int result = fileChooser.showOpenDialog( null );
if ( result == JFileChooser.APPROVE_OPTION ) // user chose a file
{
File file = null;
try
{
// get the file
File file = fileChooser.getSelectedFile();
} // end try
catch ( Exception e )
{
System.err.println( "Could not find file" );
} // end catch
if ( file != null )
{
File file = new file( );
ArrayList timeStamp = new ArrayList();
ArrayList Price = new ArrayList();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("reading");
System.out.println("Company Data");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("timeStamp");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
String timeStamp = fstNm.item(0).getNodeValue();
timeStamp.add(timeStamp);
System.out.println("timeStamp : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Price");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
String YValue = lstNm.item(0).getNodeValue();
Price.add(YValue);
System.out.println("Price : " + ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(timeStamp);
System.out.println(Price);
}
}
}
}
Any suggestions would be greatly received.
Thanks,
RebelCom.

New Topic/Question
Reply



MultiQuote




|