Java sax parser read xml example

Here's an example of using a SAX parser to read an XML document in Java:

r‮ refe‬to:theitroad.com
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 SaxParserExample extends DefaultHandler {
    public static void main(String[] args) {
        try {
            File inputFile = new File("input.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            SaxParserExample userhandler = new SaxParserExample();
            saxParser.parse(inputFile, userhandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("Start Element :" + qName);
        for (int temp = 0; temp < attributes.getLength(); temp++) {
            System.out.println("Attribute Name :" + attributes.getQName(temp));
            System.out.println("Attribute Value :" + attributes.getValue(temp));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("End Element :" + qName);
    }

    @Override
    public void characters(char ch[], int start, int length) throws SAXException {
        System.out.println("Value :" + new String(ch, start, length));
    }
}

In this example, we use the SAXParser and SAXParserFactory classes to create a SAX parser that reads the XML document from a file named input.xml. We also extend the DefaultHandler class to provide our own implementation of the methods that handle the various events that the parser generates as it reads the document.

In the startElement() method, we print out the name of the element that the parser has just encountered, along with any attributes that the element has. In the endElement() method, we simply print out the name of the element that the parser has just finished processing. In the characters() method, we print out the value of any text that the parser has just encountered.

This is just a basic example, but it should give you an idea of how to use a SAX parser to read an XML document in Java.