17.2 The XML Processing APIThe 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 APITable 17.1 lists the JAXP subset API supported by the J2ME Web Services Optional Package.
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 exampleimport 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)); } } } |