17.2 The XML Processing API The XML processing API of the J2ME Web Services Optional Package is a strict subset of JAXP v1.2. Implementations of the optional package must support the SAX v2.0 API (also see Section 15.3.1). They must support XML namespace and UTF-8 and UTF-16 encodings. DTD validation support is optional. However, if a nonvalidating parser encounters a DTD, it must throw an exception. JAXP features that are not supported include DOM and XSLT. The target runtime size for the API is about 25 KB.
17.2.1 The API Table 17.1 lists the JAXP subset API supported by the J2ME Web Services Optional Package.Table 17.1. XML API in J2ME Web Services Optional Package|
Package javax.xml.parsers | See classes below | SAXParser | The main class that controls the parsing flow and handles events via callback methods. | SAXParserFactory | The factory class that instantiates SAXParser objects. | FactoryConfigurationError | Configuration error. | ParserConfigurationException | Configuration error. | Package org.xml.sax.helpers | See classes below. | DefaultHandler | The class that the application can extend to provide custom callback handlers for parsing, validation and error events. It can be passed as a parameter to the SAXParser.parse() method. | Package org.xml.sax | See classes below. | Attributes | The interface that represents a list of XML attributes. | Locator | The interface that provides support for associating a SAX event with a document location. | InputSource | The class that encapsulates an input source in a single object. The input source can be an InputStream, a Reader or a String object. | SAXException | Runtime error. | SAXNotRecognizedException | Runtime error. | SAXNotSupportedException | Runtime error. | SAXParseException | Runtime error. | A simple example of the use of the JAXP SAX API is illustrated in Listing 17.1. The example program parses the XML file specified by the first line argument and prints out every start tag and attribute.Listing 17.1. A JAXP SAX API example
import java.io.*; import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; // Parse the XML file specified by the first // line argument and print out every start tag // and attributes public class SAXExample { public static void main(String[] args) { SAXParser parser; try { SAXParserFactory factory = SAXParserFactory.newInstance(); parser = factory.newSAXParser(); MyHandler handler = new MyHandler (); InputStream fis = new FileInputStream(args[0]); InputSource is = new InputSource (fis); parser.parse(is, handler); } catch (Exception e) { e.printStackTrace(); } } } // Define a custom callback handler class MyHandler extends DefaultHandler { public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println(qName); for (int i=0; i<attributes.getLength(); i++) { System.out.println(" " + attributes.getValue(i)); } } }
|