read xml file using sax parser in java


read xml file using sax parser in java

read xml file using sax parser in java is an important part for every java developer so let’s understand how to read xml file using sax parser in java.

Steps to read XML file  using SAx

  1. Create XML file with some data.
  2. We have to inherit DefaultHandler class in one class and we have to override required method like character(), startDocument()…etc.
  3.  Create main class and write parsing logic.

student.xml

<?xml version="1.0" encoding="UTF-8"?>
<student>
 <roll>101</roll>
 <name>Vikash</name>
 <address>Hyderabad</address>
</student>

DefaultHandler sub class

package com.javagf.sax.parser;

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

public class StudentXmlFileParser extends DefaultHandler {

 @Override
 public void characters(char[] ch, int start, int length) throws SAXException {
 String data = new String(ch, start, length);
 System.out.print(data);
 }

 @Override
 public void endDocument() throws SAXException {
 System.out.println("end document..");
 }

 @Override
 public void endElement(String uri, String localName, String qName) throws SAXException {
 System.out.print("</" + qName + ">");
 }

 @Override
 public void startDocument() throws SAXException {
 System.out.println("start document..");
 }

 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
 System.out.print("<" + qName + ">");
 }

}

Main class

package com.javagf.sax.parser;

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

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());
 }

}

Output

start document..
<student>
 <roll>101</roll>
 <name>Vikash</name>
 <address>Hyderabad</address>
</student>
end document..






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