Locating the Notified Events
In this section, you will learn to locate (line and column number) the generated events while parsing a XML file using SAX APIs.
Description of program:
This program takes a XML file at the console. Before parsing, the setContentHandler() method invokes the XMLReader object and it takes DefaultHandler object. The setContentHandler method allows an application to register a content event handler. The parser starts parsing a XML document, as soon as it encounters the root tag at at Line no: 1 Column no: 1, the startDocument() method is called and the program displays "startDocument() method called at Line no: 1 Column no: 1" at the console. When parser encounters the first elements, it calls the startElement() method and it displays "startElement() method called at Line no: 1 Column no: 19. Similarly, the parser calls characters(), endElement() and endDocument() methods. The parser displays appropriate messages according to the events generated while parsing a xml document.
Here is the XML File: sample.xml
<Employee-detail > <Employee name="Amit" > <address>My address</address> </Employee> <issued-items> <item code="111" type="CD" label=" music" /> <item code="222" type="DVD" label=" video"/> </issued-items> </Employee-detail> |
Here is Java File: WorkingSAXParserLocato.java
import java.io.*;
|
Output of this program:
C:\vinod\xml\sax1>javac WorkingSAXParserLocator.java C:\vinod\xml\sax1>java WorkingSAXParserLocator Enter xml file name: sample.xml startDocument() method called at Line no: 1 Column no: 1 startElement() method called at Line no: 1 Column no: 19 characters() method called at Line no: 2 Column no: 2 startElement() method called at Line no: 2 Column no: 25 characters() method called at Line no: 3 Column no: 3 startElement() method called at Line no: 3 Column no: 12 characters() method called at Line no: 3 Column no: 22 endElement() method called at Line no: 3 Column no: 32 characters() method called at Line no: 4 Column no: 2 endElement() method called at Line no: 4 Column no: 13 characters() method called at Line no: 5 Column no: 2 startElement() method called at Line no: 5 Column no: 16 characters() method called at Line no: 5 Column no: 17 characters() method called at Line no: 6 Column no: 3 startElement() method called at Line no: 6 Column no: 47 endElement() method called at Line no: 6 Column no: 47 characters() method called at Line no: 7 Column no: 3 startElement() method called at Line no: 7 Column no: 47 endElement() method called at Line no: 7 Column no: 47 characters() method called at Line no: 8 Column no: 2 endElement() method called at Line no: 8 Column no: 17 characters() method called at Line no: 9 Column no: 1 endElement() method called at Line no: 9 Column no: 19 endDocument() method called at Line no: 9 Column no: 19 |