SAX Locator
In this chapter you will learn:
Using XML locator to indicate current parser position
The Locator
is useful for locating
line number and column number. The following code uses
Locator to print out where the error occurs.
The Locator
is set from DefaultHandler
.
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/*from j a v a 2 s.c o m*/
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class SampleOfXmlLocator extends DefaultHandler {
private Locator locator;
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
if (qName.equals("order")) {
System.out.println("here process element start");
} else {
String location = "";
if (locator != null) {
location = locator.getSystemId(); // XML-document name;
location += " line " + locator.getLineNumber();
location += ", column " + locator.getColumnNumber();
location += ": ";
}
throw new SAXException(location + "Illegal element");
}
}
public static void main(String[] args) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
parser.parse("sample.xml", new SampleOfXmlLocator());
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML