// Hello World in XML. Parses Hello.xml file using SAX2 API.
// Adapted 3/2001 by Wayne Pollock, Tampa Florida USA
// From an artical apprearing in JavaWorld on 8-2000 by Robert Hustead,
// "Mapping XML to Java, Part 1".
// See: http://www.javaworld.com/javaworld/jw-08-2000/jw-0804-sax_p.html
//
// This program reads the file HelloXML.xml, whose top level (root) element
// "simple" should contain "name" and "location" elements. (As there is no
// definition of what HelloXML should contain, the XML contents are not
// validated (if the XML file doesn't contain the rights stuff an error
// will result). It then extracts the name and location information and
// prints a friendly greeting.
//
// Using SAX, you create a parser and provide it with an object of type
// "DefaultHandler". The parser will invoke certain methods of the
// handler whenever something interesting is seen in the input, such as
// a tag, an attribute, some data between tags, end tags, etc.
//
// In SAX the characters() method may not retieve the text in one gulp,
// instead the XML parser may call characters() multiple times. So we
// use a CharArrayWriter and append the new text each time. (This is a
// common SAX "gotcha".) Note we could have used a StringBuffer instead.
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import java.io.*;
class HelloXML extends DefaultHandler
{
private String name = "";
private String location = "";
// Buffer for collecting data from the "characters" SAX event.
private CharArrayWriter contents = new CharArrayWriter();
// Override methods of the DefaultHandler class to gain notification of SAX Events.
// (See org.xml.sax.ContentHandler for all available events.)
public void startElement ( String namespaceURI, String localName, String qName,
Attributes attr ) throws SAXException
{ contents.reset();
}
public void endElement ( String namespaceURI, String localName, String qName )
throws SAXException
{ if ( localName.equals( "name" ) )
{ name = contents.toString();
} else if ( localName.equals( "location" ) )
{ location = contents.toString();
}
}
public void characters ( char[] ch, int start, int length ) throws SAXException
{ contents.write( ch, start, length );
}
public static void main ( String [] args )
{ System.out.println( "HelloXML:" );
try
{ // Create SAX 2 parser:
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
ParserAdapter pa = new ParserAdapter( sp.getParser() );
// Set the ContentHandler:
HelloXML hello = new HelloXML();
pa.setContentHandler( hello );
// Parse the file:
pa.parse( new InputSource( new FileReader( "HelloXML.xml" ) ) );
// Say hello:
System.out.println( "Hello World from " + hello.name + " in " + hello.location );
} catch ( Exception e )
{ e.printStackTrace(); }
}
}
|