Handling XML Parser Exceptions

The handling of JADE XML Parser exceptions is similar to that for JADE XML Tree exception handling; that is, a JadeXMLException is raised when an error is detected parsing an XML document.

The methods in the following examples check that documents are well-formed. Because a tree of objects is not being created, this code checks large documents significantly faster than the documented example for the JADE XML Tree model, under "Handling XML Tree Exceptions", earlier in this chapter.

check(fileName: String);
vars
    parser : MyParser;
begin
    on JadeXMLException do checkExceptionHandler(exception);
    create parser;
    parser.parseFile(fileName);
    write fileName & ' is well-formed';
    delete parser;
end;

checkExceptionHandler(ex: JadeXMLException): Integer;
begin
    write ex.fileName & ' is not well-formed - ' & ex.extendedErrorText &
          ' at line ' & ex.lineNumber.String & ', column ' &
          ex.columnNumber.String & ': ' & ex.errorItem;
    return Ex_Abort_Action;
end;

In this example, the MyParser class has been defined as an empty subclass of the JadeXMLParser class. You do not need to implement any callback methods. If the document is not well-formed, an XML exception is raised and the checkExceptionHandler method in the previous example is invoked to print the error details.

You can also raise an exception from within your callback method to stop the parsing of the rest of the document, if required. For example, the following callback method raises an exception when it detects the specific tag for which it is searching. Your exception handler could then handle the exception to meet your requirements.

startElement(namespaceURI, localName, qualifiedName : String;
             attributeCount: Integer) updating, protected;
vars
    ex : JadeXMLException;
begin
    if qualifiedName = searchString then
        create ex;
        ex.errorCode    := MyErrorCode;      // indicate string found
        ex.fileName     := fileName;
        ex.lineNumber   := lineNumber;
        ex.columnNumber := columnNumber;
        raise ex;
    endif;
end;