有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在文件中循环计数XML元素并添加总数

我正在遍历大量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

共 (1) 个答案

  1. # 1 楼答案

    不太确定你到底想要什么。如果要添加所有文件中所有元素的结果,只需将总变量作为类的字段或外部变量,并始终将其添加到新节点列表的长度

    诸如此类:

            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 );
    

    如果这不是你想要的,请更好地解释,并张贴你的代码的其余部分。 这是未经测试的代码