Подсчитайте все предметы и отобразите на консоли - PullRequest
0 голосов
/ 08 мая 2020

У меня есть файл sample.txt, который содержит список URL-адресов файлов XML. В моей программе я читаю все эти XAML с помощью sample.txt, и мне нужно искать конкретный тег в этих XMLS. Я могу найти количество тегов в отдельном файле xaml, но не могу суммировать их все. Может ли кто-нибудь помочь мне с приведенным ниже кодом. Например, файл Sample.txt содержит 3 xmls, и в каждом есть 1 строка, которую я хочу найти. Я получаю результат как 1,1,1, но не как SUM = 3.

package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class test3 {

    public static void main(String[] args) {
        try {

            BufferedReader reader;
            ArrayList listOfFiles = new ArrayList();
            Date startTime = new Date();
            try {
                reader = new BufferedReader(new FileReader("C:\\Desktop\\Sample.txt"));
                String line = null;
                while ((line =reader.readLine()) != null) {
                    //System.out.println(line);
                    listOfFiles.add(line);
                }
                reader.close();
                System.out.println(listOfFiles);
            } catch (IOException e) {
                e.printStackTrace();
            } 

            for(int i=0; (i<listOfFiles.size() && listOfFiles.get(i) != null) ; i++){

                URL u = new URL(listOfFiles.get(i).toString());
                URLConnection uc = u.openConnection();
                String contentType = uc.getContentType();
                int contentLength = uc.getContentLength();
                if (contentType.startsWith("text/xml") || contentLength == -1) {
                  throw new IOException("This is not a binary file.");
                }
                InputStream inputFile = uc.getInputStream();

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                dbFactory.setValidating(false);
                DocumentBuilder dBuilder;
                dBuilder=dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(inputFile);
                doc.getDocumentElement().normalize();
                XPath xPath =  XPathFactory.newInstance().newXPath();
                String XPathExpression1 = "count(//ActorName[@Enabled='True'])"; 
                // Get the count of the elements with the given properties
                Number cnt1 = (Number)xPath.compile(XPathExpression1).evaluate(doc, XPathConstants.NUMBER);


                System.out.println("File:: "+ listOfFiles.get(i).toString() +" and Items:: "+cnt1.intValue());



            }


        }
        catch (ParserConfigurationException e) {
            e.printStackTrace();
        } 
        catch (SAXException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (XPathExpressionException e) {
            e.printStackTrace();
      }
    }
}

1 Ответ

0 голосов
/ 11 мая 2020

Объявите переменную суммы, например sum, и добавьте к ней cnt.intValue() внутри l oop:

        int sum = 0;

        for(int i=0; (i<listOfFiles.size() && listOfFiles.get(i) != null) ; i++){

            URL u = new URL(listOfFiles.get(i).toString());
            URLConnection uc = u.openConnection();
            String contentType = uc.getContentType();
            int contentLength = uc.getContentLength();
            if (contentType.startsWith("text/xml") || contentLength == -1) {
              throw new IOException("This is not a binary file.");
            }
            InputStream inputFile = uc.getInputStream();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setValidating(false);
            DocumentBuilder dBuilder;
            dBuilder=dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            XPath xPath =  XPathFactory.newInstance().newXPath();
            String XPathExpression1 = "count(//ActorName[@Enabled='True'])"; 
            // Get the count of the elements with the given properties
            Number cnt1 = (Number)xPath.compile(XPathExpression1).evaluate(doc, XPathConstants.NUMBER);

            sum += cnt1.intValue(); // Add to sum each time you get a count;

            System.out.println("File:: "+ listOfFiles.get(i).toString() +" and Items:: "+cnt1.intValue());



        }
       System.out.println("The sum of values is : " + sum);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...