java - 如何使用java从xml中读取一些点

标签 java xml dom

我是 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/

相关文章:

java - 在java中进行xml转换和过滤

java - 分析具有未知架构的 XML

javascript - 试图在内存游戏中显示图像

javascript - 使用 JavaScript 从指定的根节点遍历 DOM?

java - 根据值对树形图进行排序,然后将其作为树形图返回。

java - 镜像二叉树

xml - Hadoop集群设置:连接被拒绝错误

javascript - 获取 <p> 标签上的选定文本

java - 如何使用 Apache POI PPT API 设置文本字体?

sql-server - 在 SQL SERVER 中获取 XML 结构