Share on Google+Share on Google+

Getting Attributes And its Value

In this section, you will learn to retrieve the attributes and their value from a XML document using the SAX APIs.

Getting Attributes And its Value


In this section, you will learn to retrieve the attributes and their value from a XML document using the SAX APIs. 

Description of program:

This program helps you in retrieving attributes and their values.  The parse() method is  invoked by the SAXParser object. Override startElement() method in  SAXHandler class to provide functionality to get the attribute and its value from a xml file. 

Here is the XML File: sample.xml

<Employee-detail >
  <Employee name="Amit" >
  <address>My address</address>
  <item code="111" type="CD" label=" music" />
  <item code="222" type="DVD" label=" video"/>

Here is the Java File:

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.util.* ;
import org.apache.xerces.impl.*;
import org.apache.xerces.parsers.*;
import org.apache.xerces.jaxp.*;

public class ReadAttributes {
  public static void main(String[] args) {
  try {
  BufferedReader bf = new BufferedReader(
  System.out.print("Enter a xml file name: ");
  String xmlFile = bf.readLine();
  File file = new File(xmlFile);
  if (file.exists()){
  SAXParserFactory factory = SAXParserFactory.newInstance();
  // Create SAX-parser
  SAXParser parser = factory.newSAXParser();
  System.out.println("Name:\t" "Value:");
  //Define a handler
  SaxHandler handler = new SaxHandler();
  // Parse the xml document
  parser.parse(xmlFile, handler);
  System.out.println("File not found!");
  catch (Exception e) {
  private static class SaxHandler extends DefaultHandler {
  public void startElement(String uri, String localName, 
  String qName, Attributes attrs

throws SAXParseException,SAXException {
  int length = attrs.getLength();
  //Each attribute
  for (int i=0; i<length; i++) {
  // Get names and values to each attribute
  String name = attrs.getQName(i);
  String value = attrs.getValue(i);

Download this example.

Output of this program:


C:\vinod\xml\sax1>java ReadAttributes
Enter a xml file name: sample.xml
Name:  Value:
name  Amit
code  111
type   CD
label   music
code  222
type   DVD
label  video




Posted on: June 20, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Getting Attributes And its Value  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
June 13, 2012
about SaxHandler in the above program

i'm getting error for getQname() n getValue() in the sax handler
December 5, 2012
you rule

You just saved my final project! God bless you!