有 Java 编程相关的问题?

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

java中xml文件的解析列表

我试图编写java代码来解析xml文件列表。如何将这些xml文件列表传递到parse方法中

要分析文件的代码:

public void parseXml(String xmlPath, String tagName) {
        DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder docBuild = dbFact.newDocumentBuilder();
            Document dom = docBuild.parse(xmlPath);
            NodeList nl = dom.getElementsByTagName(tagName);
            System.out.println("Total tags: " + nl.getLength());
        } catch (ParserConfigurationException pe) {
            System.out.println(pe);
        }catch (SAXException se){
            System.out.println(se);
        }catch (IOException ie){
            System.out.println(ie);
        }

    }

从目录检索所有xml文件的代码:

public static List<File> getFiles(String path){
        File folder = new File(path);
        List<File> resultFiles = new ArrayList<File>();

        File[] listOfFiles = folder.listFiles();

        for(File file: listOfFiles){
            if(file.isFile() && file.getAbsolutePath().endsWith(".xml")){
                resultFiles.add(file);
            }else if(file.isDirectory()){
                resultFiles.addAll(getFiles(file.getAbsolutePath()));
            }
        }

        return resultFiles;

    }

共 (1) 个答案

  1. # 1 楼答案

    使用过滤器

    public static List<File> getFiles(String path) {
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".xml") && !name.toLowerCase().contains("settings_");
            }
        });
    
        return Arrays.asList(listOfFiles);
    }
    

    并修改您的方法以接受文件列表

    public void parseXml(List<File> xmlFiles, String tagName) {
        for (File xmlFile : xmlFiles) {
            DocumentBuilderFactory dbFact = DocumentBuilderFactory
                    .newInstance();
            try {
                DocumentBuilder docBuild = dbFact.newDocumentBuilder();
                Document dom = docBuild.parse(xmlFile);
                NodeList nl = dom.getElementsByTagName(tagName);
                System.out.println("Total tags: " + nl.getLength());
            } catch (ParserConfigurationException pe) {
                System.out.println(pe);
            } catch (SAXException se) {
                System.out.println(se);
            } catch (IOException ie) {
                System.out.println(ie);
            }
        }
    }