You'll need only the top-most file in your hierarchy for this. If you don't know which is you can first sort your list, this will put the top-most file at the first position.
String parseFile(File file, int layer) {
StringBuilder result = new StringBuilder();
if(file.isDirectory()) {
if(layer == 0) {
result.append("<root>");
for(File childFile : file.listFiles()) {
result.append(parseFile(childFile, layer + 1));
}
result.append("</root>");
}
result.append("<layer"+layer+" name=\""+file.getName()+"\">");
for(File childFile : file.listFiles()) {
result.append(parseFile(childFile, layer + 1));
}
result.append("</layer"+layer+">");
}
return result.toString();
}
This will go on until the leaf directories, if you intend to parse strictly the files on your list you'll need to test:
String parseFile(List<File> originalFileList, File file, int layer) {
StringBuilder result = new StringBuilder();
if(file.isDirectory()) {
if(layer == 0) {
result.append("<root>");
for(File childFile : file.listFiles()) {
if(originalFileList.contains(childFile)) {
result.append(parseFile(originalFileList, childFile, layer + 1));
}
}
result.append("</root>");
} else {
result.append("<layer"+layer+" name=\""+file.getName()+"\">");
for(File childFile : file.listFiles()) {
if(originalFileList.contains(childFile)) {
result.append(parseFile(originalFileList, childFile, layer + 1));
}
}
result.append("</layer"+layer+">");
}
}
return result.toString();
}