我循环遍历大量的xml文件并计算每个文件中的元素数量。我的输出列出了每个文件中的记录数,但我不确定如何将它们全部添加到一起。
package mypackage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class search {
public static void main(String[] args) throws IOException {
// Creates array of file names
String inputFile[];
String directory ="FILE DIRECTORY";
inputFile = new String[] {
file1,file2,file3,blah,blah,blah
};
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 8 * 1024);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get input element from user
System.out.print("element name: ");
String element = reader.readLine();
int total = 0;
int subTotal = 0;
for(int i=0;i<=294;i++){
Document doc = factory.newDocumentBuilder().parse(inputFile[i]);
NodeList nodes = doc.getElementsByTagName(element);
subTotal = nodes.getLength();
total =+ nodes.getLength();
System.out.println(inputFile[i] +" # of " + element + " elements " + subTotal );
}
System.out.println("Total # of " + element + " elements " + total );
} catch (Exception e) {
System.out.println(e);
}
}
}
有关澄清的其他信息。
我目前正在接受这个
file1 # of elements 4
file2 # of elements 5
file3 # of elements 6
我想要这个:
file1 # of elements 4
file2 # of elements 5
file3 # of elements 6
combined # of elements 16
更新以显示以下Brunos代码的结果:
file1 # 4
file2 # 5
file3 # 6
Total # 6
答案 0 :(得分:1)
不太确定你真正想要的是什么。如果要在所有文件中添加所有元素的结果,只需将总变量标记作为类的字段或外部变量,然后将其添加到新nodeList的长度。
类似的东西:
int total = 0;
int subTotal = 0;
for(int i=0;i<=294;i++){
Document doc = factory.newDocumentBuilder().parse(inputFile[i]);
NodeList nodes = doc.getElementsByTagName(element);
subTotal = nodes.getLength();
total += nodes.getLength();
System.out.println(inputFile[i] +" # of " + element + " elements " + subTotal );
}
System.out.println("Total # of " + element + " elements " + total );
如果它不是您要找的,请更好地解释并发布其余代码。 这是未经测试的代码。