Datasheet

Using the serializer classes is fairly straightforward. The serialization classes live in the package
org.apache.xml.serialize. All the serializers are constructed with two arguments: The first argument is an
OutputStream or Writer that is the destination for the output, and the second argument is an
OutputFormat object that controls the details of how the serializer formats its input. OutputFormats are
constructed with three arguments: a serialization method, which is a string constant taken from
org.apache.xml.serialize.Method; a string containing the desired output character encoding; and a
boolean that tells whether to indent the output. You can also construct an OutputFormat using a DOM
Document object.
Before we get into the details of OutputFormat, let’s look at how to use the serializers in a program.
We’ll look at a SAX-based version first:
1: /*
2: *
3: * SAXSerializerMain.java
4: *
5: * Example from "Professional XML Development with Apache Tools"
6: *
7: */
8: package com.sauria.apachexml.ch1;
9:
10: import java.io.IOException;
11:
12: import org.apache.xerces.parsers.SAXParser;
13: import org.apache.xml.serialize.Method;
14: import org.apache.xml.serialize.OutputFormat;
15: import org.apache.xml.serialize.XMLSerializer;
16: import org.xml.sax.SAXException;
17: import org.xml.sax.SAXNotRecognizedException;
18: import org.xml.sax.SAXNotSupportedException;
19: import org.xml.sax.XMLReader;
20:
21: public class SAXSerializerMain {
22:
23: public static void main(String[] args) {
24: XMLReader r = new SAXParser();
25: OutputFormat format =
26: new OutputFormat(Method.XML,"UTF-8",true);
27: format.setPreserveSpace(true);
28: XMLSerializer serializer =
29: new XMLSerializer(System.out, format);
30: r.setContentHandler(serializer);
31: r.setDTDHandler(serializer);
32: try {
33: r.setProperty(
34: "http://xml.org/sax/properties/declaration-handler",
35: serializer);
36: r.setProperty(
37: "http://xml.org/sax/properties/lexical-handler",
38: serializer);
39: } catch (SAXNotRecognizedException snre) {
40: snre.printStackTrace();
41: } catch (SAXNotSupportedException snse) {
35
Xerces
01 543555 Ch01.qxd 11/5/03 9:40 AM Page 35