繁体   English   中英

解析Java中的xml文件列表

[英]Parsing list of xml files in java

我正在尝试编写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;

    }

使用过滤器

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM