-
You could write your own program to process an XML document.
-
Two APIs make these programs easy to write in Java:
SAX,
DOM.
-
SAX walks through an
XML document.
It generates events for each part of a document.
-
In your Java program, you can provide an object
to handle these events.
-
DOM
builds a data structure
representing an XML document.
-
Your Java program can wander around the data structure at
will.
-
Suppose we want to write a Java program to transform some
XML
into HTML.
-
Although DOM could be used to do this,
makes more sense to use SAX.
-
Many software developers provide SAX.
-
Code you write that uses SAX is
the same
except for creating an
instance of the SAX parser.
-
Suppose we use the
Xerces parser
from the Apache Software Foundation:
XMLReader tXMLReader = new org.apache.xerces.parsers.SAXParser();
-
We also need to create the handler that is to handle the events
generated by the SAX parser:
Handler tHandler = new Handler();
-
This object then needs to be registered with the SAX parser:
tXMLReader.setContentHandler(tHandler);
-
Then the parser is let loose on the document:
FileReader tFileReader = new FileReader("consumables.xml");
InputSource tInputSource = new InputSource(tFileReader);
tXMLReader.parse(tInputSource);
-
It is the
Handler
class that is used to state what should happen when each event
arises.
-
It has to override the methods of the
DefaultHandler
class
(which has methods that do nothing).
-
For example,
consider:
public class Handler extends DefaultHandler
{
public void startElement(String pURI, String pLocalName,
String pQualifiedName, Attributes pAttributes)
{
System.out.println(pLocalName);
}
}