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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books