Java Reference
In-Depth Information
org.w3c.dom.Element string = doc.createElement("string");
string.setTextContent(text);
textElement.appendChild(string);
doc.getDocumentElement().appendChild(textElement);
}
Directory "Sketcher reading and writing XML"
Most of this code is what you have seen for other types of sketch element. Because the font style attribute
value can be "plain , " "bold , " "bold-italic , " or just "italic , " you have a series of if statements to de-
termine the attribute value. A Font object stores the style as an integer with different values for plain, bold,
and italic. The values for bold and italic may be combined, in which case the attribute value is "bold-it-
alic . "
All the element objects in a sketch can now add their own XML element nodes to a Document object.
You should now be able to use this capability to create a document that encapsulates the entire sketch.
Creating a Document Object for a Complete Sketch
You can add a createDocument() method to the SketcherFrame class to create a Document object and
populate it with the nodes for the elements in the current sketch model. Creating the Document object uses
the code fragment you saw earlier. You need to add some import statements at the beginning of the Sketch-
erFrame.java source file for the new interfaces and classes you are using:
import javax.xml.parsers.*;
import org.w3c.dom.*;
Here's the method definition you can add to the class:
// Creates a DOM Document object encapsulating the current sketch
public Document createDocument() {
Document doc = null;
try {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setValidating(true);
builderFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(this);
DOMImplementation domImpl = builder.getDOMImplementation();
Path dtdFile = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("sketcher.dtd");
doc = domImpl.createDocument(null, "sketch", domImpl.createDocumentType(
"sketch", null,
dtdFile.toString()));
} catch(ParserConfigurationException pce) {
Search WWH ::




Custom Search