【问题标题】:Searching xml file in java to see if an element exists not working?在java中搜索xml文件以查看元素是否存在不起作用?
【发布时间】:2014-07-17 18:16:42
【问题描述】:

我有一个目录,里面有 3 个文件。这应该遍历文件并处理每个 xml 文件。它会根据其中包含的元素来查找元素“Booking”或“BookingOutputPlan”,并以不同的方式进行处理。

NodeList l = null;
NodeList n = null;
int counter = 0;
for (counter = 0; counter < files.size(); counter++) {
  Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(files.get(counter));
  l = d.getElementsByTagName("Booking");
  n = d.getElementsByTagName("BookTripPlanOutput");
}

for (int i = 0; i < l.getLength(); ++i) {
  GMFiles.add(files.get(i));
  processGMXml(GMFiles, prop, log);
}
for (int a = 0; a < n.getLength(); ++a) {
  ACFiles.add(files.get(a));
  processACXml(ACFiles, prop, log);
}
}

我通过这样做得到文件的数组列表:

Properties prop = new Properties();
    InputStream in = null;
    in = new FileInputStream("config.properties");

    // load a properties file
    prop.load(in);
    in.close();

    // location of directory
    File directory = new File(prop.getProperty("directory"));

    // creates array list of files
    ArrayList<File> files = new ArrayList<File>();

    // gets all the files in that directory and puts into array
    if (directory.isDirectory()) {
        File[] listFiles = directory.listFiles();

        for (File file : listFiles) {
            if (file.isFile()) {
                files.add(file.getAbsoluteFile());
            }

        }// end of for-loop listFiles

【问题讨论】:

  • 请详细说明您的问题。有没有例外?
  • 它只处理第一个文件然后停止。它不考虑目录中的其他 2 个文件。对不起,我是解析器的新手。

标签: java xml parsing


【解决方案1】:

您正在覆盖 l 和 n 的值,因为第一个 for 循环一直运行到最后一个文件。只有 thenit 会退出循环并执行最后 2 个循环。最后两个调用解析方法的循环应该在你的第一个 for 循环中。

NodeList l = null;
NodeList n = null;
int counter = 0;
for (counter = 0; counter < files.size(); counter++) {
     Document d   =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(files.get(counter));
         l = d.getElementsByTagName("Booking");
         n = d.getElementsByTagName("BookTripPlanOutput");
        for (int i = 0; i < l.getLength(); ++i) {
                GMFiles.add(files.get(i));
                processGMXml(GMFiles, prop, log);

        }
        for (int a = 0; a < n.getLength(); ++a) {
                ACFiles.add(files.get(a));
                processACXml(ACFiles, prop, log);
         }
    }

【讨论】:

  • 为什么让它只使用第一个文件?不是最后一个文件?
  • 我试过了,但它仍然只使用第一个文件,只处理了 3 次。
  • 是的,它应该只使用最后一个文件。你确定它是第一个文件,并且在你对 parse 方法的调用中没有抛出异常
  • 你能把你的整个代码贴在这里吗?我就是这样,你的文件 ArrayList 有三次相同的文件名。告诉我你是如何得到这个数组列表的
  • 是否有不同的方法来解决这个问题而不是使用 for 循环?
【解决方案2】:

缩进有点奇怪,但我认为它的编写方式,NodeLists l 和 n 将始终只包含最后一个文件中的节点列表,因为您的初始 for 循环在解析 NodeLists 之前完全完成。

您需要将您的两个解析 for 循环需要放在初始 for 循环中。要么这样,要么在每次文件迭代时附加到您的节点列表而不是分配。

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多