SAX Locator

In this chapter you will learn:

  1. Using XML locator to indicate current parser position

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:

  1. Encode Xml Attribute
Home » Java Tutorial » XML

DOM Parser

    DOM
    Parse XML string
    Parse XML file with DOM Parser
    DOM Parser Error
    Output DOM Document to console
    Save DOM Document to a file
    Format a DOM Document
    Output Document to String
    Visit all elements
    Element retrieve by tag name
    Element character data retrieve
    DOM node visiting
    Node type
    DOM node dump
    Children nodes
    Root Element
    Doc Type
    Declared Entities
    External Entities resolve
    DOMImplementation

DOM Edit

    Element text child data
    Element remove
    Add text node to element
    Element text data update
    Add attribute to element
    Attribute remove
    Create new empty element
    Element clone
    CDATASection
    Comments element
    Processing Instruction
    New XML Document

SAX Parser

    SAX Parser action
    Parse an XML file with SAX parser
    SAX Parser based XML Document dump
    SAX Parser Error Handler
    SAX Parser content handler
    SAX Locator

Utility

    Encode String for XML attribute
    Convert Source to InputSource