Java Reference
In-Depth Information
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // Create transformer
transformer.setErrorListener(this);
transformer.transform(source, result);
// Read the XML file
theApp.insertModel(createModelFromXML(xmlDoc));
// Create the sketch
// Change file extension to .ske
currentSketchFile = setFileExtension(file, ".ske");
setTitle(frameTitle+currentSketchFile);
// Update the window
title
sketchChanged = false;
// Status is unchanged
} catch(ParserConfigurationException e) {
e.printStackTrace();
System.exit(1);
} catch(Exception e) {
System.err.println(e);
JOptionPane.showMessageDialog(this,
"Error reading a sketch file.",
"File Input Error",
JOptionPane.ERROR_MESSAGE);
}
}
Directory "Sketcher reading and writing XML"
The
DocumentBuilder
object sets the
SketcherFrame
object to be the error handler, so the methods
that you have already added to Sketcher report any parsing errors. The same applies to the
Transformer
object. The
SketcherFrame
object is the error listener, so the methods in
SketcherFrame
that implement
ErrorListener
are invoked if transformer errors occur. The
createModel()
method creates a
Sketcher-
Model
object from the
Document
object that is created from the contents of the file. You just need to imple-
ment this in
SketcherFrame
to complete reading a sketch from an XML file.
Creating the Model
You know that a sketch in XML is a two-level structure. There is a root element,
<sketch>
, that contains
one XML child element for each of the elements in the original sketch. Therefore, to re-create the sketch,
you just need to extract the children of the root node in the
Document
object and then figure out what kind
of sketch element each child represents. Whatever it is, you want to create a sketch element object of that
type and add it to a model. You have already added a constructor to each of the classes that define sketch
elements to create an object from an XML node. Here's the code for the
SketcherFrame
method that uses
them to create a sketch model:
private SketcherModel createModelFromXML(Document xmlDoc) {
SketcherModel model = new SketcherModel();
NodeList nodes = xmlDoc.getDocumentElement().getChildNodes();
// The child nodes should be elements representing sketch elements
if(nodes.getLength() > 0) {
// If there are some...