【问题标题】:Using DOM parser to output an XML file to a text file?使用 DOM 解析器将 XML 文件输出到文本文件?
【发布时间】:2015-12-01 21:24:47
【问题描述】:

好吧,在有人问我为什么对 XML 文件使用 DOM 解析器而不是 SAX 之前,原因很简单。我觉得 DOM 比 SAX 更容易使用,因为我的 XML 文件通常很小,因此通过 SAX 解析它不需要太多内存,而不是 SAX 是基于事件的 XML 解析器,它解析 XML 文件一步一步,适合大型 XML 文件。

所以现在我在这里有了这个示例 XML 文件:

<?xml version="1.0"?>
<schedule id="backup" duration="86400">
<datapoint time="0" speed="1" speednoise=".5" concurrency="8" concurrencynoise="1" interval="300" intervalnoise="300"/> <!-- 12am -->
<datapoint time="7200" speed="1" speednoise=".5" concurrency="8" concurrencynoise="1" interval="300" intervalnoise="300"/> <!-- 2am -->
<datapoint time="7201" speed="1" speednoise=".5" concurrency="0" concurrencynoise="0" interval="300" intervalnoise="300"/> <!-- 2:00:01am -->
<datapoint time="86399" speed="1" speednoise=".5" concurrency="0" concurrencynoise="0" interval="10" intervalnoise="0"/>  <!-- 11:59:59pm -->
</schedule>

我的代码:

 try {
        //this is the text file that i want to write into
        BufferedWriter writer = new BufferedWriter(new FileWriter("new_backup.txt"));
        //this is the file that i want to read from
        File fXmlFile = new File("backup.xml");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName("datapoint");
        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) node;
                System.out.println("Time : " + eElement.getAttribute("time"));
                System.out.println("Speed : " + eElement.getAttribute("speed"));
                System.out.println("SpeedNoise : " + eElement.getAttribute("speednoise"));
                System.out.println("Concurrency : " + eElement.getAttribute("concurrency"));
                System.out.println("ConcurrencyNiose : " + eElement.getAttribute("concurrencynoise"));
                System.out.println("Interval : " + eElement.getAttribute("interval"));
                System.out.println("IntervalNoise : " + eElement.getAttribute("intervalnoise"));
                if (eElement.hasChildNodes()) {
                    NodeList nl = node.getChildNodes();
                    for (int j = 0; j < nl.getLength(); j++) {
                        Node nd = nl.item(j);
                        String name = nd.getTextContent();
                        if (name != null && !name.trim().equals("")) {
                            System.out.print(name.trim() + ",");
                            //System.out.print(" ");
                            writer.write(nd.getTextContent().trim() + " ");
                        }

                    }
                    System.out.println("");
                    writer.write("\n");
                }
            }
        }
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("unused")
private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
}
}

Output: An empty text file.

我在这里做错了什么? DOM 解析器不应该在元素为“数据点”的 XML 文件的节点上工作吗?当我将输出打印到系统控制台时,它会返回我的结果,但是当我将它放入文本文件时,它是空的。我是这种解析器的新手,我正在为学校的一个项目做这个。

Console Output: Time : 0
Speed : 1
SpeedNoise : .5
Concurrency : 8
ConcurrencyNiose : 1
Interval : 300
IntervalNoise : 300
Time : 7200
Speed : 1
SpeedNoise : .5
Concurrency : 8
ConcurrencyNiose : 1
Interval : 300
IntervalNoise : 300
Time : 7201
Speed : 1
SpeedNoise : .5
Concurrency : 0
ConcurrencyNiose : 0
Interval : 300
IntervalNoise : 300
Time : 86399
Speed : 1
SpeedNoise : .5
Concurrency : 0
ConcurrencyNiose : 0
Interval : 10
IntervalNoise : 0

但它并没有像我想要的那样保存到文本文件中。

【问题讨论】:

  • 解析器用于阅读
  • 有没有办法使用其他代码将输出保存到文本文件中? @ElliottFrisch
  • 尝试将getTextContent() 的所有用法替换为getNodeValue()。 “文本内容”一般是指元素的内部内容,而不是属性的值。
  • @VGR 仍然无法工作:(

标签: java xml parsing dom


【解决方案1】:

请在写有writer.close();的行之前添加writer.flush();

close() 通常也会调用 flush(),但我总是调用 writer.flush();。 原因是在某些 JDK 实现中,作为关闭的一部分由刷新引发的任何异常都会被吞没。这是相关的线程:difference between flush and close function in case of filewriter in java。向下滚动到@Jon Skeet 答案

【讨论】:

  • 来自documentation for the close() method:“关闭流,先刷新它。” close() 总是意味着 flush()。
  • @VGR 您会根据更新后的评论重新考虑否决票吗?
  • 即使在 Jon 提到的 JDK 实现中,flush() 也总是被调用。
【解决方案2】:

您的外部for 循环正在迭代&lt;datapoint&gt; 元素。这些元素没有任何子节点(&lt;datapoint/&gt; 是一个空元素),因此永远不会输入 if 语句,这意味着永远不会向 writer 写入任何内容。

您可能打算为您的数据点元素迭代 属性。由于属性顺序可能是任意的,因此迭代不是最优的,因此您应该按名称获取它们,就像您在 print 语句中所做的那样。

【讨论】:

  • 但即使我这样做了,它也不会改变任何东西,因为这个“数据点”元素被用来从文件中获取属性并将其输出到控制台中。这是我的理解,如果我错了,我对Java还是比较陌生。 :(
  • 我的第二段是指 inner 迭代,而不是外循环。
猜你喜欢
  • 2013-12-24
  • 2011-12-15
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
相关资源
最近更新 更多