Java Reference
In-Depth Information
StreamResult xmlFile = new StreamResult(xmlOut);
transformer.transform(source, xmlFile);
// Write XML to file
} catch (TransformerConfigurationException tce) {
System.err.println("Transformer Factory error: " + tce.getMessage());
} catch (TransformerException te) {
System.err.println("Transformation error: " + te.getMessage());
} catch (IOException e) {
System.err.println("I/O error writing XML file: " + e.getMessage());
}
}
Directory "Sketcher reading and writing XML"
You first create a
Document
object for the sketch by calling the
createDocument()
method that you ad-
ded to
SketcherFrame
earlier in this chapter. You create an output stream corresponding to the
Path
object
that is passed to the method in the
try
block. To create a
Transformer
object that writes the file, you first
create a
TransformerFactory
object by calling the static
newInstance()
method. Calling the
newTrans-
former()
method with no arguments for the factory object creates a
Transformer
object that represents an
identity transform. You set the
SketcherFrame
object to be the error listener for the
Transformer
object so
SketcherFrame
needs to implement the
ErrorListener
interface.
You set the values for two properties for the transformer. You set the value for
INDENT
key to “yes" so
whitespace is inserted between elements in the output and the value for
DOCTYPE_SYSTEM
key to the file path
for the DTD.
To write the file, you define the
Document
object as the source for the transform and the
xmlFile
output
stream object as the result. Calling
transform()
for the
transformer
object with these as arguments writes
the file.
To implement the
ErrorListener
interface in the
SketcherFrame
class, first amend the first line of the
class definition:
public class SketcherFrame extends JFrame
implements ActionListener, Observer, Printable, ErrorHandler, ErrorListener {
Next add definitions for the methods declared in the interface:
// Handles recoverable errors from transforming XML
public void error(TransformerException te) {
System.err.println("Error transforming XML: " + te.getMessage());
}
// Handles fatal errors from transforming XML
public void fatalError(TransformerException te) {
System.err.println("Fatal error transforming XML: " + te.getMessage());
System.exit(1);
}
// Handles warnings from transforming XML
public void warning(TransformerException te) {
System.err.println("Warning transforming XML: " + te.getMessage());