Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias 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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close