I am trying to write java code to parse list of xml files. How do I pass those list of xml files into parse method.
Code to parse file:
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);
}
}
Code to retrieve all xml files from directory:
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;
}
Use filters
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);
}
And modify your method to accept list of files
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.