Java Reference
In-Depth Information
The DOM Document object provides no convenient way to get a complete XML document as a string
or series of strings. The toString() method for a Node object looked hopeful in this respect - at least
for the Crimson parser, but we saw that what the toString () method produced depended on the
parser so we can't rely on that. The only way is for us to slog it out for ourselves. Our
writeXMLFile() method will have to navigate the Document object and its nodes in order to create
all the well-formed and valid XML that has to be written to the file to form a complete XML document.
Creating an XML document won't be difficult. We already know how to navigate a Document object
and write the nodes to the command line. We did that in an example a few pages back. We will need to
make sure the code we use here writes everything we need to produce well-formed XML but it will be
essentially the same as what we have seen. The only difference here is that we are writing to a file
channel rather than the command line but that should not be any trouble since we know how to do that,
too. If we take a little care in the appearance of the XML, we should be able to end up with an XML file
defining a sketch that is reasonably readable.
Since we want to be able to look at the XML file for a sketch in an editor, we will write is as the 8-bit
Unicode subset UTF-8 . With all that knowledge and experience, we can implement writeXMLFile()
in the SketchFrame class like this:
private void writeXMLFile(org.w3c.dom.Document doc, FileChannel channel) {
StringBuffer xmlDoc = new StringBuffer(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlDoc.append(NEWLINE).append(getDoctypeString(doc.getDoctype()));
xmlDoc.append(getDocumentNode(doc.getDocumentElement(), ""));
try {
channel.write(ByteBuffer.wrap(xmlDoc.toString().getBytes("UTF-8")));
} catch(UnsupportedEncodingException e) {
System.out.println(e.getMessage());
} catch(IOException e) {
JOptionPane.showMessageDialog(SketchFrame.this,
"Error writing XML to channel.",
"File Output Error",
JOptionPane.ERROR _ MESSAGE);
e.printStackTrace(System.err);
return;
}
}
Initially we create a StringBuffer object that will eventually contain the entire XML document. It
starts out initialized with the XML declaration and we append the text corresponding to the DOCTYPE
declaration. We use the getDoctypeString() method to generate this and this method will be
virtually identical to the method of the same name from the example earlier in this chapter, as we shall
see in a moment. This method accepts an argument of type DocumentType , assembles a complete
DOCTYPE delcaration from that, and returns it as type String . This is appended to xmlDoc following a
newline character that will start the declaration on a new line.
We introduce another new method in the code for the writeXMLFile() method in the statement:
Search WWH ::




Custom Search