Java Reference
In-Depth Information
JOptionPane.ERROR _ MESSAGE);
e.printStackTrace();
}
}
Most of the code here is devoted to catching exceptions that we hope will not get thrown. We set up the
parser factory object to produce a validating parser that will ignore surplus whitespace. The latter feature will
avoid extraneous nodes in the Document object that will be created by the parser from the XML file.
After storing a reference to the DOM parser that is created in builder , we create a
DOMErrorHandler object and set that as the handler for any parsing errors that arise. If the parser
finds any errors, we will see a dialog displayed indicating what the error is. We use the builder object
to parse the XML file that is identified by the File object, xmlFile and pass the Document object
that is returned by the parse() method to the createSketchModel() method that we will be
adding to the SketchFrame class next. This method has the job of creating a new SketchModel
object from the Document object.
Let's see how we can create a new SketchModel object encapsulating a new sketch by analyzing the
Document object.
Creating the Model
We know that a sketch in XML is a two-level structure. There is a root element, <sketch> , that
contains one XML element for each of the elements in the original sketch. Therefore to recreate the
sketch, we 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, we want to create a sketch element
object of that type and add it to a model. The simplest way to create sketch element objects from a
given document node is to add a constructor to each of the classes that define sketch elements. We will
add these constructors after we have defined the createSketchModel() method in the
SketchFrame class. Here's the code for that:
private SketchModel createSketchModel(org.w3c.dom.Document doc) {
SketchModel model = new SketchModel(); // The new model object
// Get the first child of the root node
org.w3c.dom.Node node = doc.getDocumentElement().getFirstChild();
// Starting with the first child, check out each child in turn
while (node != null) {
assert node instanceof org.w3c.dom.Element; // Should all be Elements
String name = ((org.w3c.dom.Element)node).getTagName(); // Get the name
if(name.equals("line")) // Check for a line
model.add(new Element.Line((org.w3c.dom.Element)node));
else if(name.equals("rectangle")) // Check for a rectangle
model.add(new Element.Rectangle((org.w3c.dom.Element)node));
else if(name.equals("circle")) // Check for a circle
Search WWH ::




Custom Search