How do I get attributes of element during SAX parsing?

This example show you how to get the attributes of elements in an XML file using the SAX parser.

package org.kodejava.xml;

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

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

public class SAXElementAttribute {
    public static void main(String[] args) {
        SAXElementAttribute demo = new SAXElementAttribute();;

    private void run() {
        try {
            // Create SAXParserFactory instance and a SAXParser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            // Get an InputStream to the elements.xml file and parse
            // its contents using the SAXHandler.
            InputStream is =
            DefaultHandler handler = new SAXHandler();
            parser.parse(is, handler);
        } catch (Exception e) {

    static class SAXHandler extends DefaultHandler {
        public void startElement(String uri, String localName,
                                 String qName, Attributes attributes)
                throws SAXException {

            int attributeLength = attributes.getLength();
            if ("person".equals(qName)) {
                for (int i = 0; i < attributeLength; i++) {
                    // Get attribute names and values
                    String attrName = attributes.getQName(i);
                    String attrVal = attributes.getValue(i);
                    System.out.print(attrName + " = " + attrVal + "; ");

The elements.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
        <person name="Foo" age="25" />
        <person name="Bar" age="22" />

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.