[英]How can I take XML attribute and find a file that matches the attribute value in a given directory java
我有一个Java程序,该程序读取xml文件并获取属性并将该值打印到屏幕上。 现在,我想获取每个属性的值并搜索目录以查找与该给定属性匹配的所有文件。
我的代码如下:
public class ReadXML {
public static void main(String[] args) {
try {
File fXmlFile = new File("////Orders//188219.outorder");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("seln_part");
File dir = new File("////Images//Parts");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
FileFilter filter;
System.out.println("Part Number : " + eElement.getAttribute("partNumber"));
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
我现在想获取eElement.getAttribute("partNumber")
的值,并在images / parts目录中搜索任何匹配项。
我该怎么做呢?
您可以通过以下两个步骤来实现。
步骤1:将所有文件名及其绝对路径存储在哈希图中,如下所示,
HashMap<String,String> fileNamevsPathMap = new HashMap<String,String>();
String rootDirectory = "Your Directory Path to Search";
boolean isRecursive = true;
Collection files = FileUtils.listFiles(rootDirectory, null, isRecursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
fileNamevsPathMap .put(file.getName(),file.getAbsolutePath()
}
第2步:使用哈希图搜索您的匹配项
if(fileNamevsPathMap.containsKey(eElement.getAttribute("partNumber"))){
System.out.println("Part Number absolute path : "+fileNamevsPathMap.get(eElement.getAttribute("partNumber")));
}else{
System.out.println("Part Number Not found on directory");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.