Java Reference
In-Depth Information
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
These cover the new classes that we used in our new code for I/O and for DOM without using fully
qualified names.
Try It Out - Writing a Sketch as XML
Recompile sketcher with the new code. Once you have fixed any errors you can run Sketcher and
export your sketch as XML. You can then inspect the file in your editor. You can also process the file
with our
TryDOM
and
TrySAX
programs to check that the XML is valid.
How It Works
We have been through the detailed mechanics of this. The
SketchModel
object creates a
Document
object
that is populated by nodes encapsulating the sketch elements. Each node is created by the corresponding
sketch element. We then navigate through the nodes in the document to create the XML for each node.
We can now have a go at importing an XML sketch.
Reading an XML Representation of a Sketch
The
Import XML
operation will also be implemented in the
SketchFrame
class. We have already
added the menu item and the
XMLImportAction
class that is used to create it. We just need to
implement the
openXMLSketch()
method that is called by the
actionPerformed()
method in the
XMLImportAction
class.
Assuming our XML representation of a sketch is well-formed and valid, creating a
Document
object
encapsulating a sketch will be a piece of cake. We will just get a DOM parser to do it - and it will verify
that the document is well-formed and valid along the way. We will need an
ErrorHandler
object to
deal with parsing errors, so let's add an inner class to our
SketchFrame
class for that:
class DOMErrorHandler implements org.xml.sax.ErrorHandler {
public void fatalError(org.xml.sax.SAXParseException spe)
throws org.xml.sax.SAXException {
JOptionPane.showMessageDialog(SketchFrame.this,
"Fatal error at line "+spe.getLineNumber()
+ "\n"+spe.getMessage(),
"DOM Parser Error",
JOptionPane.ERROR
_
MESSAGE);
throw spe;
}
public void warning(org.xml.sax.SAXParseException spe) {
JOptionPane.showMessageDialog(SketchFrame.this,
"Warning at line "+spe.getLineNumber()
+ "\n"+spe.getMessage(),
"DOM Parser Error",