Ad

Wednesday 18 June 2014

Parsing XML using stax parser in Java

STAX API uses the pull parsing methodology,where we call the methods on the Stax Library and depending on the events returned we get the values from the XML.When parsing using STAX,it will return the different events depending on the XML element type which it is current referring to.

Lets say we want to parse the below XML and we need to set the values in the Employee object.

employee.xml

<?xml version="1.0" encoding="UTF-8"?>                                                                                        
<employeedetails>
  <employee id="1">
<name>Rahul</name>
<age>25</age>
               <department>IT</department>
    </employee>
    <employee id="2">
<name>John</name>
<age>26</age>
               <department>IT</department>
    </employee>
    <employee id="3">
<name>Peter</name>
<age>29</age>
                <department>HR</department>
    </employee>
</employeedetails>

Employee.java

public class Employee {

private String empId=null;                                                                                                          
private String empName=null;
private String age=null;
private String department=null;

/**
* @return the empId
*/
public String getEmpId() {
return empId;
}

/**
* @param empId the empId to set
*/
public void setEmpId(String empId) {
this.empId = empId;
}

/**
* @return the empName
*/
public String getEmpName() {
return empName;
}

/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}

/**
* @return the age
*/
public String getAge() {
return age;
}

/**
* @param age the age to set
*/
public void setAge(String age) {
this.age = age;
}

/**
* @return the department
*/
public String getDepartment() {
return department;
}

/**
* @param department the department to set
*/
public void setDepartment(String department) {
this.department = department;
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", age="
+ age + ", department=" + department + "]";
}
}



Below is the sample code for parsing the employee.xml and to set the value in list of employee object.

import java.io.InputStream;  
import java.util.ArrayList;
import java.util.List;
                                                                                                                                                             
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
                                                                                                                                                               
public class StaxExample {

public static void main(String[] args) {
      List<Employee> employeeList=null;
      Employee employee=null;
      try
      {
      XMLInputFactory inputFactory= XMLInputFactory.newFactory();
      InputStream inputStream=StaxExample.class.getClassLoader().
                                                 getResourceAsStream("employee.xml");
      XMLStreamReader xmlStreamReader=inputFactory.createXMLStreamReader(inputStream);
      String elementName="";
      while(xmlStreamReader.hasNext())
      {
     int event=xmlStreamReader.next();
     if(event==XMLStreamConstants.START_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employeedetails".equalsIgnoreCase(elementName))
     {
     employeeList=new ArrayList<Employee>();
     }
     else if("employee".equalsIgnoreCase(elementName))
     {  
     employee=new Employee();
     if(xmlStreamReader.getAttributeCount()>0 && 
     ("id").equalsIgnoreCase(xmlStreamReader.getAttributeLocalName(0)))
     employee.setEmpId(xmlStreamReader.getAttributeValue(0));
     }
     }
     else if(event==XMLStreamConstants.CHARACTERS)
     {
     String value=xmlStreamReader.getText();
     if(elementName.equalsIgnoreCase("name"))
     {
     employee.setEmpName(value);
     }
     else if(elementName.equalsIgnoreCase("age"))
     {
     employee.setAge(value);
     }
     else if(elementName.equalsIgnoreCase("department"))
     {
     employee.setDepartment(value);
     }
     }
     else if(event==XMLStreamConstants.END_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employee".equalsIgnoreCase(elementName))
     {
     employeeList.add(employee);
     }
     elementName="";//Reset the elementName(TagName)
     }
      }
      System.out.println("Values Parsed from XML is:"+employeeList.toString());
      }
      catch(Exception e)
      {
     e.printStackTrace();
      }
  }
}

  • The starting point of using STAX API is to get the XMLInputFactory Object.
  • Then we get the XMLStreamReader from this factory by passing the inputstream for the xml to be parsed.Make sure the employee.xml is in the classpath.
  • XMLStreamReader behaves as the pointer to the xml and when we invoke the next() method ,it will return the event of the Current xml element type and moves to next element in the xml.
  • When the start element of any xml tag is reached,it will return the event XMLStreamConstants.START_ELEMENT.Then by using the getLocalName() method we can get the name of the xml tag.To get the value of the attribute in the current element, we can use the method getAttributeValue(index),where index is the position of the attribute in in the corresponding tag
  • When the end element of any xml tag is reached,it will return the event XMLStreamConstants.END_ELEMENT
  • when the value of any tag is reached,it will return the event XMLStreamConstants.CHARACTERS and we can use the method getText() to get the value enclosed within the tag
OUTPUT


Values Parsed from XML is:[Employee [empId=1, empName=Rahul, age=25, department=IT],   Employee [empId=2, empName=John, age=26, department=IT], Employee [empId=3, empName=Peter, age=29, department=HR]]                                                                                     

Friday 13 June 2014

How to implement SelectAll Checkbox using Jquery

Some times we may need to implement the Selectall checkbox in our pages.On Checking the Select all check box,it will check all the check boxes under it and unchecking it,will deselect all the Check boxes.Jquery sample for Select All functionality is shown below

<html>
  <head>
    <title>Selecall Checkbox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function() {
     
     /*Handler For SelectAll Checkbox*/ 
      $("#selectallchkbox").change(function(){
        $('.tvChkBox').prop("checked",$(this).prop("checked"));
       });

      /*Handler For rest of the checkbox*/      
       $('.tvChkBox').change(function(){
       if( $('.tvChkBox').length==$('.tvChkBox:checked').length)
         {
           $("#selectallchkbox").prop("checked",true);    
         }
         else
         {
           $("#selectallchkbox").prop("checked",false);
         }         
       });

    });
</script>
</head>
<body>
<table bgcolor="#E9E9E9" border="1">
<tr>
<td>
<B>Selectall Sample</B><BR><BR>
<table border='1'>
<tr>
<th><input type="checkbox" id="selectallchkbox"/></th>
<th>TV Brand</th>
<th>Rank</th>
</tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox1"/></td><td>Sony</td><td>1</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox2"/></td><td>Samsung</td><td>3</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox3"/></td><td>LG</td><td>2</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox4"/></td><td>Onida</td><td>4</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>

  • When the page document is ready(i.e on load of the page),the Javascript code inside the $(document).ready will be get executed.
  • We registered two handlers in the ready section.
  • Change Handler for SelectAll CheckBox- On change of SelectAll check box,if it is checked we select all the Checkboxes with the class "tvChkBox" and  if it is unchecked we uncheck the same(by setting the property "checked" to true or false).
  • Change Handler for rest of the Checkboxes - On change of the Checkboxes with the class "tvChkBox",if all the Checkboxes with  the class "tvChkBox" is checked we will check the selectall Checkbox,otherwise will uncheck the selec all checkbox(by setting the property "checked" to true or false).  
 Demo:


Selectall Sample

TV Brand Rank
Sony1
Samsung3
LG2
Onida4

Thursday 12 June 2014

How to load dropdown list dynamically using Jquery

In most scenarios we may need to load the drop down list dynamically with the values fetched from the database.Using jquery loading the dropdown list is very simple and easy to code.Lets assume we need to load the drop down with the city names fetched from the backend.The sample code for this is shown below:

<html>                                                                                                                                                    
<head>
<title>Dropdown sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function Load() {
   var cityobjArray = [
  {cityId:1,cityName:"Chennai"},
  {cityId:2,cityName:"Mumbai"},
  {cityId:3,cityName:"Banglare"},
  {cityId:4,cityName:"Pune"},
   ];
var cityDropdown = $('#cityDrpDown');

$.each(cityobjArray , function(index, cityobj) {
        cityDropdown.append(
         $('<option/>', {
                          value: cityobj.cityId,
                          text: cityobj.cityName
                        })
           );
        });
}

function unLoad() {
 $('#cityDrpDown').empty();
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<B>To Load DropdownList dynamically</B><BR><BR>
Select City:<select  id="cityDrpDown"/></select>
<BR><BR>
<input type="button" value="Load" onclick="Load()"/>
<input type="button" value="Unload" onclick="unLoad()"/>
</td>
</tr>
</table>
</body>
</html>

  • Lets assume cityobjectArray is the Json data array we fetched from database which we need to load in the drop down list.
  • As shown in Load method,we iterate the cityobjectArray using $.each jquery method and for each cityobject we add the option object ("referenced using $(<option/>") to the dropdown list.The value and text of the Option object will set from Cityobject attributes cityid and cityname. 
  • To clear the dropdown list we use the jquery method empty() as shown in unLoad() method.

Demo:


To Load DropdownList dynamically

Select City:



Wednesday 11 June 2014

To check/uncheck the Checkboxes using Jquery


We may need to precheck a check box, when the page loads or we may need to check it depending on any event.Using Jquery it is very simple and easy to implement.Below is the sample code to check or uncheck a single check box or all checkboxes.

<html>                                                                                                                                                    
<head>
<title>CheckBox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function check() {
   $("#checkbox1").prop("checked", true);
}

function uncheck() {
   $("#checkbox1").prop("checked", false);
}

function checkall() {
   $("#checkGrp input[type=checkbox]").each(function()
    {
      $(this).prop("checked",true);
    } );
}

function uncheckall() {
   $("#checkGrp input[type=checkbox]").each(function()
   {
    $(this).prop("checked",false);
   });
}
</script>
</head>
<body bgcolor=white>

<input type="checkbox" id="checkbox1"/>BreakFast
<BR>
<input type="button" value="check" onclick="check()"/>
<input type="button" value="uncheck" onclick="uncheck()"/>
<BR><BR>
<div id="checkGrp">
<input type="checkbox" id="checkbox2"/>Coffee
<BR>
<input type="checkbox" id="checkbox3"/>Tea
<BR>
<input type="checkbox" id="checkbox4"/>Bread
<BR>
<input type="checkbox" id="checkbox5"/>Burger
<BR>
<input type="button" value="CheckAll" onclick="checkall()"/>
<input type="button" value="UncheckAll" onclick="uncheckall()"/>
</div>
</body>
</html>

  • To check the Checkbox,we set the Property of the checkbox with id "checkbox1" to true as shown in function check()
  • To uncheck the Checkbox,we set the Property of the checkbox with id "checkbox2" to false as shown in function uncheck()
  • To checkall the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to true as shown in function checkall().
  • To uncheck all the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to false as shown in function uncheckall().

Demo

BreakFast


Coffee
Tea
Bread
Burger