Parsing an XML Document

To parse an XML document

  1. In your client application, define a subclass of the JadeXMLParser class.

  2. Implement any callback methods that you require; for example, the startElement, endElement, and characters methods.

  3. Create an instance of the JadeXMLParser subclass and call the parseFile or parseString method.

The following example parses a document and prints the names of the elements in that document, indented to show the hierarchy.

listElements(fileName: String);
vars
    parser : MyParser;
begin
    create parser;
    parser.parseFile(fileName);
    delete parser;
end;

The MyParser class is a subclass of the JadeXMLParser class and it has a single Integer attribute depth that keeps track of the current element indent level.

The MyParser class implements the following client callback methods.

startElement(namespaceURI, localName, qualifiedName: String;
             attributeCount: Integer) updating, protected;
vars
    i   : Integer;
    str : String;
begin
    foreach i in 1 to depth do
        str := str & '  ';
    endforeach;
    write str & qualifiedName;
    depth := depth + 1;
end;

endElement(namespaceURI: String; localName: String;
           qualifiedName: String) updating, protected;
begin
    depth := depth - 1;
end;

As the parser reads the input file, it recognizes the start and end of each element and invokes the startElement and endElement callback methods in the previous example. The startElement method prints the indentation and the name of the current element, and increments the hierarchy depth. The endElement method decrements the hierarchy depth. The following is output when the listElements method is run on the library1.xml document.

library
  book
    title
    author
  book
    title
    author