Yet another Java XML API: xmlpull (1/2) - exploring XML | WebReference

Yet another Java XML API: xmlpull (1/2) - exploring XML

Yet another Java XML API: xmlpull

XML processing is moving into the non-PC space, with PDAs and mobile phones acting as Web service clients and synchronizing their content with desktops via SyncML. Conserving heap and stack memory is a key requirement in this environment. With xmlpull, a new API has been devised for parsing XML.

Really new, or hardly used?

What seems like a radically new idea is actually an evolution of a familiar pattern in disguise, used in Java's input/output library. This author remembers when he implemented his first XML parser, consisting of XMLReader, XMLToken and XMLException, used like this:

XMLReader reader = new XMLReader(new FileReader("blah.xml"));
try {
  while (reader.isAvailable()) {
    XMLToken token = reader.read();
	switch (token) {
      case XMLTOKEN.START_TAG:
	  case XMLTOKEN.END_TAG:
	  case XMLTOKEN.TEXT:
        // process token
	}
  }
}
catch (IOException ex) {
  // something went wrong with the underlying file
}
catch (XMLException ex) {
  // something is wrong with the XML (e.g. not well-formed)
}

The .NET API sports an XMLReader component with a similar API, and one of the first fully compliant XML parsers, expat, utilizes the xmltok API for token-based access to an XML data stream. Java also has StringTokenizer and StreamTokenizer for arbitrary data streams that work along the same lines. But since imitation is the sincerest form of flattery, let's look at xmlpull in more detail.

xmlpull pulled apart

The xmlpull API also consists of three classes, XMLPullParser, XMLPullParserFactory, and XMLPullException. The design of these classes is odd to say the least.

XMLPullParserFactory creates instances of XMLPullParsers. While it is common practice to have parser factories, I'm glad that the Java language designer decided not to use the factory pattern everywhere, otherwise we would be dealing with StringFactory, all over the place, and common idioms like

Reader r = new InputStreamReader(new FileInputStream(new File(new String("file.txt"))));

would have to become:

StringFactory sf = StringFactory.newInstance();
String s = sf.newString();
s.setContent("file.txt");
FileFactory ff = FileFactory.newInstance();
File f = ff.newFile();
f.setFilename(s);
FileInputStreamFactory fisf = FileInputStreamFactory.newInstance();
FileInputStream fis = fisf.newFileInputStream();
fis.setFile(f);
InputStreamReaderFactory isrf = InputStreamReaderFactory.newInstance();
InputStreamReader isr = isrf.newInputStreamReader();
isr.setFileInputStream(fis);

Argh! Some people have to put the pattern design books aside, at least for a while.

More funnies...


Produced by Michael Claßen

URL: https://www.webreference.com/xml/column76/index.html
Created: Mar 03, 2003
Revised: Mar 03, 2003