Home » Core Java » xml » SAX » Get element attributes in SAX XML parsing

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services, currently the technical lead in a in-house PCRF solution. Particularly interested in multi-tier architecture, middleware services and mobile development (contact). Ilias Tsagklis is co-founder and Executive Editor at Java Code Geeks.

Get element attributes in SAX XML parsing

In this example we shall show you how to get an Element’s Attributes using SAX XML parsing. Simple API for XML (SAX) is an event-driven, serial-access mechanism for accessing XML documents. It is frequently used by servlets and network-oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents, other than the Streaming API for XML (StAX). We have created a Class, GetElementAttributesInSAXXMLParsing that is a handler that extends the DefaultHandler and overrides its startElement(String uri, String localName, String qName, Attributes attributes) API method. The basic steps of the example are described below:

  • Create a new instance of the GetElementAttributesInSAXXMLParsing class.
  • Obtain a new instance of a SAXParserFactory, that is a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
  • Set the parser produced by this code so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of SAXParserFactory with validating set to false.
  • Create a new instance of a SAXParser, using newSAXParser() API method of SAXParserFactory.
  • Use parse(File f, DefaultHandler dh) API method of SAXParser to parse the content of the specified XML file, using the specified handler of the example. The handler that we have implemented, overrides the startElement(String uri, String localName, String qName, Attributes attributes) API method of DefaultHandler. In this method, for each one of the given Attributes it takes its qualified (prefixed) name, its value, namespace URI and local name, using getQName(int index), getValue(int index), getURI(int index) and getLocalName(int index) API methods of Attributes,

as described in the code snippet below. 

package com.javacodegeeks.snippets.core;

import java.io.File;

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

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

public class GetElementAttributesInSAXXMLParsing extends DefaultHandler {
	
	public static void main(String[] args) throws Exception {
		
		DefaultHandler handler = new GetElementAttributesInSAXXMLParsing();

		SAXParserFactory factory = SAXParserFactory.newInstance();

  factory.setValidating(false);

  

  SAXParser parser = factory.newSAXParser();

  

  parser.parse(new File("in.xml"), handler);
		
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		// get the number of attributes in the list

  int length = attributes.getLength();


  // process each attribute

  for (int i=0; i<length; i++) {

  	


// get qualified (prefixed) name by index


String name = attributes.getQName(i);


System.out.println("Name:" + name);





// get attribute's value by index.


String value = attributes.getValue(i);


System.out.println("Value:" + value);



// get namespace URI by index (if parser is namespace-aware)


String nsUri = attributes.getURI(i);


System.out.println("NS Uri:" + nsUri);



// get local name by index


String lName = attributes.getLocalName(i);


System.out.println("Local Name:" + lName);




  }
		
	}

}

Input:

<?xml version="1.0" encoding="UTF-8" ?>
<response code="200" description="OK">
	<date zone="UTC">2008-11-07</date>
	<title>Exchange rates for 2008-11-07</title>
</response>

Output:

Name:code
Value:200
NS Uri:
Local Name:code
Name:description
Value:OK
NS Uri:
Local Name:description
Name:zone
Value:UTC
NS Uri:
Local Name:zone

  
This was an example of how to get an Element’s Attributes using SAX XML parsing in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.