0

I have successfully parsed an XML file in Java and I can read and print values.

public static void main (String args[]) {

    try{
        String XML = "test.xml";

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File(XML));

I now would like to parse a directory of XML and continue to do the same ( read and print). Im thinking a simple .txt file with XML filepaths:

"test.xml"
"sample.xml"
"name.xml"
2
  • ... and your question is? Commented Nov 13, 2014 at 14:11
  • I am not sure what the question is. Commented Nov 13, 2014 at 14:13

1 Answer 1

1

If you want to process all XML files in the directory, you can use a FileFilter.

Sample code:

// Directory where the files are located
File dir = new File("xml_folder");

// Create a FileFilter that matches ".xml" files
FileFilter filter = new FileFilter() {
    @Override
    public boolean accept(File file) {
       return file.isFile() && file.getName().endsWith(".xml");
    }
};

// Get pathnames of matching files.
File[] paths = dir.listFiles(filter);

You can then use a for loop to iterate through the paths array and parse each file as you wish.

If you are using Java 1.8 or for anyone who is and wants the above in Lambda expression form then you can use:

// Directory where the files are located
File dir = new File("xml_folder");

// Create a FileFilter that matches ".xml" files
FileFilter filter = (File file) -> file.isFile() && file.getName().endsWith(".xml");

// Get pathnames of matching files.
File[] paths = dir.listFiles(filter);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.