Tuesday, August 27, 2013

DOM XML Parser


In Java JDK 2 built-in XML parsers are available.
* DOM
* SAX

DOM XML Parser

The DOM is the easiest to use Java XML Parser. It parses an entire XML document and load it into memory.

pros : modeling it with Object for easy model traversal.

Cons : DOM Parser is slow and consume a lot memory if it load a XML document which contains a lot of data.
       i. DOM parser passes the entire XML document and loads into the memory.
       ii. Then model it is in a “Tree” structure for easy traversal or manipulation.

       By using DOM XML Parser
           * can read a XML file
           * can create a XML file
           * can modify XML file
                  i. Add a new element
                  ii. Update existing element attribute
                  iii. Update existing element value
                  iv. Delete element
           * can count the total number of elements in a XML file. First, search the element name, and then you can use NodeList.getLength() to get the total number of available elements.


package DOMXMLParser;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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


public class DOMXMLParserExample {

       /**
       * @param args
       */
      public static void main(String[] args) {

           DOMXMLParserExample xmlFile = new DOMXMLParserExample();
           //read the XML
           xmlFile.readXML();
           //loop node one by one
           xmlFile.loopNodes();
           //write the XML
           xmlFile.writeXML();
           //modify the XML
           xmlFile.modifyXML();
           //count XML elements
           xmlFile.countElements();
     }

     private void readXML(){

          try{
              File fXmlFile = new File("/home/sanjeeva/Desktop/employee.xml");
              DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
              DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
              Document doc = dBuilder.parse(fXmlFile);

              doc.getDocumentElement().normalize(); //This is optional; but recommended

              String rootElement = doc.getDocumentElement().getNodeName();
              System.out.println("rootElement --> " + rootElement);
              NodeList nList = doc.getElementsByTagName("staff"); 
 
              System.out.println("----------------------------");
              for (int temp = 0; temp < nList.getLength(); temp++) {
                   Node nNode = nList.item(temp);
                   System.out.println("\nCurrent Element :" + nNode.getNodeName());

                   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                         Element eElement = (Element) nNode;
                         System.out.println("Staff id : " + eElement.getAttribute("id"));
                         System.out.println("First Name : " + eElement.getEementsByTagName("firstname").item(0).getTextContent());
                         System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                         System.out.println("Designation : " + eElement.getElementsByTagName("designation").item(0).getTextContent());
                         System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
                  }
              }

          }catch (Exception e) {
           e.printStackTrace();
          }
     }
 
     private void loopNodes(){
 
          try{
             File file = new File("/home/sanjeeva/Desktop/employee.xml");
             DocumentBuilder dBuilder =      DocumentBuilderFactory.newInstance().newDocumentBuilder();
             Document doc = dBuilder.parse(file);
             System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

             if (doc.hasChildNodes()) {
                  printNote(doc.getChildNodes());
             }
         }catch (Exception e) {
              e.printStackTrace();
         }
     }

     private void printNote(NodeList nodeList) {

         for (int count = 0; count < nodeList.getLength(); count++) {
              Node tempNode = nodeList.item(count); 
 
              //make sure it's element node.
              if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                  System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
                  System.out.println("Node Value =" + tempNode.getTextContent());

                  if (tempNode.hasAttributes()) {
                       // get attributes names and values
                       NamedNodeMap nodeMap = tempNode.getAttributes();

                       for (int i = 0; i < nodeMap.getLength(); i++) {
                            Node node = nodeMap.item(i);
                            System.out.println("attr name : " + node.getNodeName());
                            System.out.println("attr value : " + node.getNodeValue());
                       }
                  }
                  if (tempNode.hasChildNodes()) {
                       //loop again if has child nodes
                       printNote(tempNode.getChildNodes());
                  }
                  System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");
             }
         }
    }

    private void writeXML(){
 
         try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("company");
            doc.appendChild(rootElement);
 
             // staff elements
             Element staff = doc.createElement("Staff");
             rootElement.appendChild(staff);

             // set attribute to staff element
             Attr attr = doc.createAttribute("id");
             attr.setValue("100");
             staff.setAttributeNode(attr);

             // firstname elements
             Element firstname = doc.createElement("firstname");
             firstname.appendChild(doc.createTextNode("Thinuli"));
             staff.appendChild(firstname);

             // lastname elements
             Element lastname = doc.createElement("lastname");
             lastname.appendChild(doc.createTextNode("Pathirana"));
             staff.appendChild(lastname);

             // designation elements
             Element designation = doc.createElement("nickname");
             designation.appendChild(doc.createTextNode("Project Manager"));
             staff.appendChild(designation);
 
             // salary elements
             Element salary = doc.createElement("salary");
             salary.appendChild(doc.createTextNode("100000"));
             staff.appendChild(salary);
   
             // write the content into xml file
             TransformerFactory transformerFactory = TransformerFactory.newInstance();
             Transformer transformer = transformerFactory.newTransformer();
             DOMSource source = new DOMSource(doc);
             StreamResult result = new StreamResult(new File("/home/sanjeeva/Desktop/employeeWrite.xml"));
              // Output to console for testing
              // StreamResult result = new StreamResult(System.out);
              transformer.transform(source, result);
              System.out.println("File saved!");
          } catch (ParserConfigurationException pce) {
               pce.printStackTrace();
          } catch (TransformerException tfe) {
               tfe.printStackTrace();
          }
     }

     private void modifyXML(){
 
           try {
                String filepath = "/home/sanjeeva/Desktop/employeeWrite.xml";
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(filepath);
                 
                // Get the root element
                Node company = doc.getFirstChild();
                // Get the staff element by tag name directly
                //Node staff = doc.getElementsByTagName("staff").item(0); //
                Node staff = company.getFirstChild();
                // update staff attribute
                NamedNodeMap attr = staff.getAttributes();
                Node nodeAttr = attr.getNamedItem("id");
                nodeAttr.setTextContent("2");
                // append a new node to staff
                Element age = doc.createElement("age");
                age.appendChild(doc.createTextNode("28"));
                staff.appendChild(age);
                    
                // loop the staff child node
                NodeList list = staff.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                     Node node = list.item(i);
                     // get the salary element, and update the value
                     if ("salary".equals(node.getNodeName())) {
                           node.setTextContent("2000000");
                     }
                     //remove firstname
                     if ("firstname".equals(node.getNodeName())) {
                           staff.removeChild(node);
                     }
               }
               // write the content into xml file
               TransformerFactory transformerFactory = TransformerFactory.newInstance();
               Transformer transformer = transformerFactory.newTransformer();
               DOMSource source = new DOMSource(doc);
               StreamResult result = new StreamResult(new File(filepath));
         
               transformer.transform(source, result);
               System.out.println("Modification Done");

         } catch (ParserConfigurationException pce) {
               pce.printStackTrace();
         } catch (TransformerException tfe) {
               tfe.printStackTrace();
         } catch (IOException ioe) {
               ioe.printStackTrace();
         } catch (SAXException sae) {
               sae.printStackTrace();
         }
    }

    private void countElements(){
 
         try {
               String filepath = "/home/sanjeeva/Desktop/employee.xml";
               DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
               DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
               Document doc = docBuilder.parse(filepath);
    
               NodeList list = doc.getElementsByTagName("staff");
               System.out.println("Total of elements : " + list.getLength());
          } catch (ParserConfigurationException pce) {
                pce.printStackTrace();
          } catch (IOException ioe) {
                ioe.printStackTrace();
          } catch (SAXException sae) {
                sae.printStackTrace();
          }
    }
}

Write XML -

<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>Sanjeeva</firstname>
<lastname>Pathirana</lastname>
<designation>Software Engineer</designation>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>Sandamali</firstname>
<lastname>Silva</lastname>
<designation>Network Engineer</designation>
<salary>200000</salary>
</staff>
</company>