Java Reference
In-Depth Information
System.err.println("Transformer Factory error: " + tce.getMessage());
} catch (TransformerException te) {
System.out.println("Transformation error: " + te.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
The process is very simple. You use the TransformerFactory object you have created to create the
Transformer object. You set the property value for the transformer that corresponds to the INDENT key con-
stant in the javax.xml.transform.OutputKeys class. This class defines constants that identify property
keys for Transformer objects. Setting the value for INDENT to “yes" makes the transformer insert addition-
al whitespace in the output so that elements appear on separate lines. With the default “no" value for the
property, the output would not contain any newline characters between elements and so would be difficult
to read. Instead of using the OutputKeys constant, you could use the String that is the key, “ indent ," but
using the constant is the preferred approach. With the T ransformer object set up, you create the Source ob-
ject from the root node in the xmlDoc object. You create the Result object from the output stream, xmlOut ,
that encapsulates the file.
Transformer Properties
The OutputKeys class defines the following static fields that identify property keys for a Transformer ob-
ject (see Table 23-2 ):
TABLE 23-2 : OutputKeys Constants that Identify Transformer Properties
FIELD NAME VALUE FOR KEY
INDENT "yes" causes the processor to insert whitespace in the output. Default is “no."
DOCTYPE_SYSTEM The system identifier to be used in the DOCTYPE declaration as a string.
DOCTYPE_PUBLIC The public identifier to be used in the DOCTYPE declaration as a string.
ENCODING The encoding to be used for the output.
MEDIA_TYPE The MIME content type for the result tree.
CDATA_SECTION_ELEMENTS A list of element names whose text child nodes should be output as CDATA .
OMIT_XML_DECLARATION "yes" causes the processor to omit the XML declaration in the output. The default is “no."
STANDALONE
"yes" causes the processor to output a standalone document declaration.
Specifies the method to be used for the result tree, for example, “xml," “html," or “text."
METHOD
The version of the output method.
VERSION
I'm only using the first two OutputKeys fields from the table. The DOCTYPE_SYSTEM property value is
required for a DOCTYPE declaration to be included in the output, and you use this in Sketcher.
Dealing with Transformer Errors
A Transformer object can report errors by calling methods declared by the
javax.xml.transform.ErrorListener interface. You can specify an object that is an error listener for a
Transformer object like this:
transformer.setErrorListener(errorListener);
 
 
Search WWH ::




Custom Search