在java中搜索xml文件以查看是否存在无法工作的元素?
我有一个目录,里面有3个文件。这应该循环遍历文件并处理每个xml文件。它查找元素Booking或BookingOutputPlan,这取决于它包含的元素,它以不同的方式处理在java中搜索xml文件以查看是否存在无法工作的元素?,java,xml,parsing,Java,Xml,Parsing,我有一个目录,里面有3个文件。这应该循环遍历文件并处理每个xml文件。它查找元素Booking或BookingOutputPlan,这取决于它包含的元素,它以不同的方式处理 NodeList l = null; NodeList n = null; int counter = 0; for (counter = 0; counter < files.size(); counter++) { Document d = DocumentBuilderFactory.newInstance(
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);
}
}
我通过以下操作获取文件的arraylist:
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
缩进有点奇怪,但我认为它的编写方式,节点列表l和n总是只包含最后一个文件中的节点列表,因为您的初始for循环在解析节点列表之前完成
您需要将两个解析for循环放入初始for循环中。或者,在每次文件迭代时将其附加到节点列表中,而不是赋值。由于第一个for循环一直运行到最后一个文件,因此将覆盖l和n的值。只有这样,它才会退出循环并执行最后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);
}
}
请进一步解释你的问题。是否有异常?它只处理第一个文件,然后停止。它不考虑目录中的其他2个文件。对不起,我是新来的解析器。为什么这会使它只使用第一个文件?不是最后一个文件?我试过了,但它仍然只使用第一个文件,只处理了3次。是的,它应该只使用最后一个文件。您确定这是第一个文件,并且在对parse方法的调用中没有引发异常吗?您可以在这里发布您的全部代码吗?如果是这样,您的文件数组列表有三次相同的文件名。告诉我你是如何得到这个数组列表的有没有一种不同的方法来代替for循环?