我是 XML 新手,我想将 XML 文件中的点附加到我编写的点容器中。
这是 XML 文件:
<?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>
这就是我所做的:
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));
}
}
我的问题是它循环一次。
最佳答案
nList
包含 container
节点列表,并且 XML 文档中只有一个这样的元素。您需要改为获取 point
元素:
NodeList nList = doc.getElementsByTagName("container");
Element containerElement = (Element) nList.item(0);
NodeList pointNodes = containerElement.getElementsByTagName("point");
for(int i = 0; i < pointNodes.getLength(); i++) {
Element point = (Element) pointNodes..item(i);
...
关于java - 如何使用java从xml中读取一些点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28094662/