how to read few points from xml using java



I'm new to XML and I want to append points from an XML file to a point container that I wrote.


this is the XML file:



<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<container>
<point>
<X>56</X>
<Y>58</Y>
</point>
<point>
<X>59</X>
<Y>40</Y>
</point>
<point>
<X>70</X>
<Y>30</Y>
</point>
</container>


this is what I did:



private void OpenFile () throws ParserConfigurationException, SAXException, IOException {
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
while (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, Please select txt file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
of = new JFileChooser();
option = of.showOpenDialog(of);
}
if (option == JFileChooser.APPROVE_OPTION){
thisFile = new File(of.getSelectedFile().getPath());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(thisFile);
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("container");
Element line = (Element) nList.item(0);
for(int i =0 ; i < nList.getLength() ; i++) {
Element point = (Element) line.getElementsByTagName("point").item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
}


my problem that it loop one time.


No comments:

Post a Comment