0

It is possible to read the complete content of a xml files inside a folder with java?

My code is:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();      
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(new FileInputStream(new 
File("C:\\Users\\Administrator\\eclipse-workspace\\XMLExamples2\\")));

Element element = (Element) doc.getElementsByTagName("composite").item(0);

// Adds a new attribute. If an attribute with that name is already present 
// in the element, its value is changed to be that of the value parameter
element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-
instance");
element.setAttribute("xsi:noNamespaceSchemaLocation", "v1_6.xsd");

I'm just able to read and manipulate single files when it put the name after ...\XMLExample2\

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Speedec
  • 13
  • 5
  • 1
    Well yes - so loop over all the files in the folder, and load one at a time. – Jon Skeet Jul 19 '17 at 13:21
  • Use [File#listFiles()](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()) and parse each one – Socratic Phoenix Jul 19 '17 at 13:21
  • 1
    You have to read the file from the directory in a loop like in the below example. https://stackoverflow.com/questions/3154488/how-do-i-iterate-through-the-files-in-a-directory-in-java – user8271644 Jul 19 '17 at 13:22

2 Answers2

1

No, you can't process the content of multiple XML files as a unique document.

But you may list the XML files then process each File from the list :

String xmlDir = "C:\\Users\\Administrator\\eclipse-workspace\\XMLExamples2";
File[] files = new File(xmlDir).listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File folder, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });

for(File file : files){

    Document doc = db.parse(file);

    Element element = (Element) doc.getElementsByTagName("composite").item(0);

    // etc...

}
Arnaud
  • 17,229
  • 3
  • 31
  • 44
-1

Each file is a seperate document. So, if you aren't trying to read them as a single document, then all you need to do is grab a list of files in that folder using the File class' listFiles() method. You can then loop over each file in the folder and process them accordingly.

If you do want to treat it as a single XML document: you will need to merge the files together first, and then process it. There are a number of ways that can be done. You may want to look at this question for a couple ideas.

MBurnham
  • 381
  • 1
  • 9