Java Reference
In-Depth Information
}
Directory "Sketcher reading and writing XML"
Each method just outputs an error message. With a fatal error, you abort the program. You could throw
TransformerException if you want to simply stop the transformer. Some more import statements are
needed in SketcherFrame.java :
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import javax.xml.validation.*;
You should be able to recompile Sketcher at this point if you want to try out writing a sketch as XML.
The file that is produced should be quite readable, and you can view it using any plain text editor, such as
Notepad.
READING AN XML REPRESENTATION OF A
SKETCH
Reading a sketch from an XML file is the reverse of writing it. You can use a Transformer object to create
a Document object from the XML markup in the file. You can then iterate through the child nodes in the
Document object and create sketch Element objects from them. You need a way to create sketch elements
from the XML elements, and the obvious way to tackle this is to add constructors to the classes derived
from the Element class that create an object from the Node object that encapsulates the XML for the ele-
ment. These new instructors must be able to call a base class constructor as the first statement. However, the
existing Element class constructors are not suitable because they require arguments that are not available
when one of the new constructors starts executing. Let's see how you can accommodate this and provide for
initializing the base class fields.
Creating the Base Class Object from XML
You can add a no-arg constructor to the Sketcher Element class to solve the problem:
protected Element() {}
This constructor creates the object but does not initialize the base class fields. That is down to the derived
class constructors.
If the Element class has methods to initialize its fields from an XML node object, these can be used by all
of the derived classes when an object is to be created from XML. Here's the method to initialize the angle
field:
Search WWH ::




Custom Search