Java program to parse xml file

Similar question:

  • How to read XML file in Java
  • java dom parser
  • java sax parser
  • listing all the files in a directory in java
Solution:

Config.xml
 <note>

  <id>1</id>
  <description>Files</description>
  <path>C://x</path>
  
    <id>2</id>
  <description>Files</description>
  <path>C://y</path>
</note>



  1. import java.io.File;
  2. import org.w3c.dom.*;

  3. import javax.xml.parsers.*;


  4. public class XML {

  5. public static void main(String[] args) {
  6. try {
  7.         File inputFile = new File("C://Config.xml");
  8.         DocumentBuilderFactory dbFactory 
  9.            = DocumentBuilderFactory.newInstance();
  10.         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  11.         Document doc = dBuilder.parse(inputFile);
  12.         doc.getDocumentElement().normalize();
  13.         NodeList nList = doc.getElementsByTagName("ID");
  14.         for (int temp = 0; temp < nList.getLength(); temp++) {
  15.            Node nNode = nList.item(temp);
  16.            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
  17.               Element eElement = (Element) nNode;
  18.               String description =  eElement.getElementsByTagName("description").item(0).getTextContent();
  19.               System.out.println(description);
  20.               String path = eElement.getElementsByTagName("path").item(0).getTextContent();
  21.                
  22.               final File folder = new File(path);
  23.               for (final File fileEntry : folder.listFiles()) {               
  24.              if (fileEntry.isDirectory()) {
  25.               System.out.println(fileEntry.getAbsolutePath());
  26.              } else { 
  27.         System.out.println(fileEntry.getAbsolutePath());
  28.               }   
  29.          }
  30.            }
  31.         }
  32.      } catch (Exception e) {
  33.         e.printStackTrace();
  34.      }
  35. }
  36. }

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation