-3

I need to read all the input xml files from the folder and write one output text file, comma separated. I have the following code program read one file, can someone please help me to modify it and read all the files from the c:/java/ folder. thanks

   import java.io.IOException;
   import org.w3c.dom.*;
   import org.xml.sax.SAXException;
   import javax.xml.parsers.*;
   import javax.xml.xpath.*;

    public class XPathExample {

        public static void main(String[] args) throws ParserConfigurationException,
                SAXException, IOException, XPathExpressionException {

            DocumentBuilderFactory domFactory = DocumentBuilderFactory
                    .newInstance();
            domFactory.setNamespaceAware(true); 
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc = builder.parse("c:/java/test.xml");

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//FORM[@name='F00001']        /*/text()");

            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
            }

            }

             }
A Par
  • 17
  • 1
  • 2
  • 4

2 Answers2

0

Use this to iterate all files in your directory:

Read all files in a folder

Output (file in dir) use as input here

Document doc = builder.parse("<dir file>");

If file is not xml, it either return null or exceprion is raised (I dont know currently). Eitherway, you will have to solve this.

Community
  • 1
  • 1
Martin Perry
  • 9,232
  • 8
  • 46
  • 114
0

To get all the files in the directory C:\java you can use the code:

for (File file : new File("C:\\java").listFiles()) 
{
   Document doc = builder.parse(file.getAbsolutePath());
   ...
}

You can play about with where you add the rest of your code around this loop. You should also add some basic checks that what you're trying to parse is indeed XML too.

Nick Holt
  • 33,455
  • 4
  • 52
  • 58