how to convert xml to java object using sax parser

How to convert xml to java object using sax parser

Let’s understand how to convert XML to java object using sax parser with simple example, SAX parser is a sequential XML parser in java.


  1. class for saving xml data into object.
  2. student.xml file
  3. as an sub class of DefaultHandler
  4. SaxParser as a main class

package com.javagf.beans;


public class StudentDto implements Serializable {
 protected String roll;
 protected String name;
 protected String address;

 public String getRoll() {
 return roll;

 public void setRoll(String roll) {
 this.roll = roll;

 public String getName() {
 return name;

 public void setName(String name) { = name;

 public String getAddress() {
 return address;

 public void setAddress(String address) {
 this.address = address;

 public String toString() {
 return "StudentDto [roll=" + roll + ", name=" + name + ", address=" + address + "]";



<?xml version="1.0" encoding="UTF-8"?>

package com.javagf.sax.parser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.javagf.beans.StudentDto;

public class StudentXmlFileParser extends DefaultHandler {
 String data = null;
 StudentDto dto = new StudentDto();
 boolean roll;
 boolean name;
 boolean address;

 public void characters(char[] ch, int start, int length) throws SAXException {
 data = new String(ch, start, length).trim();

 if (roll) {
 roll = false;
 } else if (name) {
 name = false;
 } else if (address) {
 address = false;

 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
 if (qName.equals("roll")) {
 roll = true;
 } else if (qName.equals("name")) {
 name = true;
 } else if (qName.equals("address")) {
 address = true;

 public void endDocument() throws SAXException {



package com.javagf.sax.parser;


import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class SaxParser {
 private static final String STUDENT_FILE_PATH = "D:\\REST\\ListenerExample\\xml\\student.xml";

 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
 SAXParser saxParser = saxParserFactory.newSAXParser();
 saxParser.parse(new File(STUDENT_FILE_PATH), new StudentXmlFileParser());



StudentDto [roll=101, name=Vikash, address=Hyderabad]

Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: Sales: +91 8085506229