Thursday, August 3, 2017

How to Read XML in Java – (DOM Parser)

In this Example I will demonstrate how to read and modify xml file using DOM parser:

Step 1. Read an xml file from disk or project directory
Step 2. Build an xml document form the xml file
Step 3. Retrive and update xml element and attribute

Course.xml file

       


<?xml version="1.0" encoding="UTF-8"?>  
<courses>     
   <course category="JAVA">  
      <title lang="en">Learn Java in 3 Months.</title>  
      <trainer>Sonoo Jaiswal</trainer>  
      <year>2008</year>  
      <fees>10000.00</fees>  
   </course> 
    <course category="XML">  
      <title lang="en">Learn XML in 2 Months.</title>  
      <trainer>Ajeet Kumar</trainer>  
      <year>2015</year>  
      <fees>4000.00</fees>  
   </course>    
</courses> 
       
 




           import java.io.File;  
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; 

/**
 * @author Md. Shariful Islam
 
*/
public class XMLDOMTester{

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  //String filepath = "c:\\Course.xml"; 
  
  File xmlFile = new File("Course.xml");
  boolean exist = xmlFile.exists();
  System.out.println(exist);
  
  
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder;
  try {
   docBuilder = docFactory.newDocumentBuilder();
   Document xmlDocument = docBuilder.parse(xmlFile);
   
   //optional, but recommended
   //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
   xmlDocument.getDocumentElement().normalize();
   
   String rootElement =  xmlDocument.getDocumentElement().getNodeName();
   System.out.println("Root element :" +rootElement);
   
   NodeList nList = xmlDocument.getDocumentElement().getChildNodes();
   
   for (int i = 0; i < nList.getLength(); i++) {
    
    Node node = nList.item(i);
    
    if (node.getNodeType() == node.ELEMENT_NODE) {
     
     String nodeName = node.getNodeName();
     System.out.println(nodeName);
     
    }
   }
   
   
   
  } catch (ParserConfigurationException | SAXException | IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  

       
 

For modifying XML file Please read the follwing blog

how-to-modify-xml-file-in-java-dom-parser


No comments:

Post a Comment

5 Strategies for Getting More Work Done in Less Time

Summary.    You’ve got more to do than could possibly get done with your current work style. You’ve prioritized. You’ve planned. You’ve dele...