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>
- import java.io.File;
- import org.w3c.dom.*;
- import javax.xml.parsers.*;
- public class XML {
- public static void main(String[] args) {
- try {
- File inputFile = new File("C://Config.xml");
- DocumentBuilderFactory dbFactory
- = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse(inputFile);
- doc.getDocumentElement().normalize();
- NodeList nList = doc.getElementsByTagName("ID");
- for (int temp = 0; temp < nList.getLength(); temp++) {
- Node nNode = nList.item(temp);
- if (nNode.getNodeType() == Node.ELEMENT_NODE) {
- Element eElement = (Element) nNode;
- String description = eElement.getElementsByTagName("description").item(0).getTextContent();
- System.out.println(description);
- String path = eElement.getElementsByTagName("path").item(0).getTextContent();
- final File folder = new File(path);
- for (final File fileEntry : folder.listFiles()) {
- if (fileEntry.isDirectory()) {
- System.out.println(fileEntry.getAbsolutePath());
- } else {
- System.out.println(fileEntry.getAbsolutePath());
- }
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Comments
Post a Comment