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.example.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;
import java.io.InputStream;

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

    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 =
                    getClass().getResourceAsStream("/elements.xml");
            DefaultHandler handler = new SAXHandler();
            parser.parse(is, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class SAXHandler extends DefaultHandler {
        @Override
        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 + "; ");
                }
                System.out.println("");
            }
        }
    }
}

The elements.xml file is as follow:

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

How do I handle error when parsing an XML file using SAX?

The ErrorHandler interface implemented by the org.xml.sax.helpers.DefaultHandler class provides some methods for error handling mechanism in SAX parsing. The methods are warning(), error(), and fatalError().

package org.kodejava.example.xml;

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

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;

public class SAXErrorHandlerDemo {
    public static void main(String[] args) throws Exception {
        SAXErrorHandlerDemo demo = new SAXErrorHandlerDemo();
        demo.run();
    }

    public void run() throws Exception {
        // Creates the SAXParserFactory and SAXParser instance.
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        // Parse the error.xml file using MySAXHandler as the 
        // DefaultHandler implementation.
        InputStream is = getClass().getResourceAsStream("/error.xml");
        DefaultHandler handler = new MySAXHandler();
        parser.parse(is, handler);
    }

    // Override the error handling methods defined by the ErrorHandler
    // interface. This method will handler exceptions thrown by the
    // parsing process.
    class MySAXHandler extends DefaultHandler {
        @Override
        public void warning(SAXParseException e) throws SAXException {
            System.out.println("warning   : " + e.getMessage());
        }

        @Override
        public void error(SAXParseException e) throws SAXException {
            System.out.println("error     : " + e.getMessage());
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            System.out.println("fatalError: " + e.getMessage());
        }
    }
}