Saturday 31 May 2014

Read, Write and Delete XML based on Query

Hello Guys, Hope you all doing well !!!..
Today I am going to share an example of Xml Read, writer and Delete functionality based on query. Yes!!!..
Just like Sql DB query you can also read write and delete a particular XML File Tag. It is done by Using XPath Xml Reader in Java. And It is quite useful for Large XML File in which a particular Node Element Tag have to read, write and Update. XPath is a language for finding information in an XML file. You can say that XPath is (sort of) SQL for XML files. XPath is used to navigate through elements and attributes in an XML document. You can also use XPath to traverse through an XML file in Java.
Here is the a sample xml file and we are going use it for this example:-
<?xml version="1.0"?>
<Employees>
    <Employee emplid="1030" type="admin">
        <firstname>Saurabh</firstname>
        <lastname>Sharma</lastname>
        <age>28</age>
        <email>saurabh.sharma569@gmail.com</email>
    </Employee>
    <Employee emplid="1040" type="admin">
        <firstname>Sherlock</firstname>
        <lastname>Homes</lastname>
        <age>32</age>
        <email>sherlock@sh.com</email>
    </Employee>
    <Employee emplid="1050" type="user">
        <firstname>Anup Kumar</firstname>
        <lastname>Singh</lastname>
        <age>26</age>
        <email>aone_anup33@gmail.com</email>
    </Employee>
    <Employee emplid="1060" type="user">
        <firstname>Super Man</firstname>
        <lastname>Holmes</lastname>
        <age>31</age>
        <email>super_man@sh.com</email>
    </Employee>
        <Employee emplid="1070" type="user">
        <firstname>Himat Singh</firstname>
        <lastname>Negi</lastname>
        <age>31</age>
        <email>negi_himat@yopmail.com</email>
    </Employee>
        <Employee emplid="1080" type="user">
        <firstname>RaajVir Singh</firstname>
        <lastname>Raghuvansi</lastname>
        <age>41</age>
        <email>rajvir@yopmail.com</email>
    </Employee>
</Employees>
In order to understand XPath, first we need to understand basics of DOM parsing in Java. Java provides powerful implementation of domparser.
First, we need to create a document builder using DocumentBuilderFactory class. Once we have a document builder object. We uses it to parse XML file and create a document object.Once we have document object. We are ready to use XPath. Just create an xpath object using XPathFactory.
  please following the online comment in code for better understanding..
package com.sks.mks;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; 
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XpathXmlExample { 
       FileInputStream file = null;
       DocumentBuilderFactory builderFactory = null;
       DocumentBuilder builder = null;
       Document xmlDocument = null;
       XPath xPath = null;
        //created document builder object.
       //We uses it to parse XML file and create a document object
       //Once we have document object. We are ready to use XPath.
       //Just create an xpath object using XPathFactory.
       public XpathXmlExample() {
              try{
                      file = new FileInputStream(new File("C:/Users/Abc/Desktop/employee_detail.xml"));

                     builderFactory = DocumentBuilderFactory.newInstance();

                     builderbuilderFactory.newDocumentBuilder();

                     xmlDocument = builder.parse(file);

                     xPath =  XPathFactory.newInstance().newXPath();

              } catch (FileNotFoundException e) {
                     e.printStackTrace();
              } catch (ParserConfigurationException e) {
                     e.printStackTrace();
              } catch (SAXException e) {
                     e.printStackTrace();
              } catch (IOException e) {
                     e.printStackTrace();
              }     
       }
       public static void main(String[] args) {
              //1. Read firstname of all employees
              new XpathXmlExample().readFistNameOfEmployees("/Employees/Employee/firstname");
             
              //2.Read a specific employee using employee id
              new XpathXmlExample().readSpecificEmployeeById("/Employees/Employee[@emplid='1030']");
             
              //3. Read firstname of all employees who are admin
              new XpathXmlExample().readAdminEmployee("/Employees/Employee[@type='admin']/firstname");
             
              //4. Delete an Employee based on Id
              new XpathXmlExample().deleteOldTags("/Employees/Employee[@emplid='1080']");
             
              //4. Write an new Employee Detail based on Id
              new XpathXmlExample().writeNewTags("/Employees/Employee[@emplid='1080']", "firstname", "Himanshu", "lastname", "Kumar", "age", "32", "email", "himashu.45@yopmail");
             

       }
       public void readFistNameOfEmployees(String expression){
              System.out.println(expression);
              NodeList nodeList = null;
              try {
                     nodeList = (NodeList)xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
                     for (int i = 0; i < nodeList.getLength(); i++) {
                           System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
                     }
              } catch (XPathExpressionException e) {
                     e.printStackTrace();
              }
       }

       public void readSpecificEmployeeById(String expression){
              System.out.println(".....................................");
        System.out.println(expression);
        Node node = null;
        NodeList nodeList = null;
              try {
                     node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
               if(null != node) {
                    nodeList = node.getChildNodes();
                   for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
                       Node nod = nodeList.item(i);
                       if(nod.getNodeType() == Node.ELEMENT_NODE)
                           System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue());
                   }
               }
              } catch (XPathExpressionException e) {
                     e.printStackTrace();
              }
       }
      
       public void readAdminEmployee(String expression){
               System.out.println("*************************");
         System.out.println(expression);
         NodeList nodeList;
              try {
                     nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
                     for (int i = 0; i < nodeList.getLength(); i++) {
                    System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
                    nodeList.item(i).getLastChild().getNodeValue();
                }
              } catch (XPathExpressionException e) {
                     e.printStackTrace();
              }
       }
      
       public void writeNewTags(String expression, String Val_1_Name, String Val_1_value, String Val_2_Name, String Val_2_value,String Val_3_Name,String Val_3_value,String Val_4_Name,String Val_4_value){
              try{                
                     System.out.println("-----------------------------------------------------");
                     System.out.println(expression);
                     Node node2 = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

                     if(null != node2) {
                           Element EmployeeFisrtName = xmlDocument.createElement(Val_1_Name);
                           EmployeeFisrtName.appendChild(xmlDocument.createTextNode(Val_1_value));
                           Element EmployeeLastName = xmlDocument.createElement(Val_2_Name);
                           EmployeeLastName.appendChild(xmlDocument.createTextNode(Val_2_value));
                           Element EmployeeAge = xmlDocument.createElement(Val_3_Name);
                           EmployeeAge.appendChild(xmlDocument.createTextNode(Val_3_value));
                           Element EmployeeEmail = xmlDocument.createElement(Val_4_Name);
                           EmployeeEmail.appendChild(xmlDocument.createTextNode(Val_4_value));

                           node2.appendChild(EmployeeFisrtName);
                           node2.appendChild(EmployeeLastName);
                           node2.appendChild(EmployeeAge);
                           node2.appendChild(EmployeeEmail);

                           try {
                                  // write the DOM object to the file
                                  TransformerFactory transformerFactory = TransformerFactory.newInstance();
                                  Transformer transformer = transformerFactory.newTransformer();
                                  DOMSource domSource = new DOMSource(xmlDocument);
                                  StreamResult streamResult = new StreamResult(new File("C:/Users/Abc/Desktop/employee_detail.xml"));
                                  transformer.transform(domSource, streamResult);
                                  System.out.println("The XML File was updated");
                           } catch (TransformerConfigurationException e) {
                                  e.printStackTrace();
                           } catch (TransformerFactoryConfigurationError e) {
                                  e.printStackTrace();
                           } catch (TransformerException e) {
                                  e.printStackTrace();
                           }
                           catch (Exception e) {
                                  e.printStackTrace();
                           }
                     }

              } catch (XPathExpressionException e) {
                     e.printStackTrace();
              } catch (DOMException e) {
                     e.printStackTrace();
              }
              catch (Exception e) {
                     e.printStackTrace();
              }
       }

      
       public void deleteOldTags(String expression){
              try{
                     NodeList nodeList = null;
                     //expression= "/DisplaySettings/Pages/Page[@PageID='4010']/Sorting/Column";
                     System.out.println(expression);
                     Node node2 = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

                     // at first removing...
                     if(null != node2) {
                            nodeList = node2.getChildNodes();
                           System.out.println("NodeList Size:="+nodeList.getLength());
                           for (int i = nodeList.getLength() - 1; i >= 0; i--) {
                                  try {
                                         //Element e = (Element)nodeList.item(i);
                                         Node no1 = (Node) nodeList.item(i);
                                         no1.getParentNode().removeChild(no1);
                                         //e.getParentNode().removeChild(e);

                                  } catch (NullPointerException e) {
                                         // TODO Auto-generated catch block
                                         e.printStackTrace();
                                  }
                           }
                           try {
                                  // write the DOM object to the file
                                  TransformerFactory transformerFactory = TransformerFactory.newInstance();
                                  Transformer transformer = transformerFactory.newTransformer();
                                  DOMSource domSource = new DOMSource(xmlDocument);
                                  StreamResult streamResult = new StreamResult(new File("C:/Users/Abc/Desktop/employee_detail.xml"));
                                  transformer.transform(domSource, streamResult);
                                  System.out.println("The XML File was updated");
                           } catch (TransformerConfigurationException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (TransformerFactoryConfigurationError e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (TransformerException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }catch (Exception e) {
                                  e.printStackTrace();
                           }
                     }

              } catch (XPathExpressionException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (DOMException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }catch (Exception e) {
                     e.printStackTrace();
              }
       }        
}

This is all about read write and delete xml by using Xpath in java. You have to copy and paste above code in Java class and create a xml file by using given xml file. you can check more on Xpath in java by using following link :- 

Thanks Happy Coding!!!

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...