Configures XML settings

def write(self, document):

settings = XmlWriterSettings ( ) settings.Indent = True settings.IndentChars = ' ' settings.OmitXmlDeclaration = True self.writer = XmlWriter.Create(self.fileName, settings)

self.writer.WritestartDocument()

self.writer.WritestartElement("document")

Creates writer object

Writes each page in document for page in document: <-

self.writePage(page)

self.writer.WriteEndElement() self.writer.WriteEndDocument() self.writer.Close()

def writePage(self, page) :

self.writer.WriteStartElement("page")

self.writer.WriteAttributeString("title", page.title) self.writer.WriteString(page.text) self.writer.WriteEndElement()

This class needs to be saved as the file documentwriter.py. To plug this into MultiDoc, you need to modify the commands to use it. First, DocumentWriter needs to be imported inside the savecommands module.

from documentwriter import DocumentWriter

The SaveAsCommand inherits from SaveCommand, and the file writing is done in the saveFile method. You can get most of the way toward the changes you want by modifying saveFile as follows:

def saveFile(self, fileName, document): try:

writer = DocumentWriter(fileName) writer.write(document) return True except IOError, e:

Previously the execute and promptAndSave methods of the commands only needed to pass some text to saveFile; now they need to pass the document instead. The document still needs to be updated before saving, so getText becomes getUpdatedDocument.

def getUpdatedDocument(self):

self.tabController.updateDocument() return self.document

The execute method of both SaveCommand and SaveAsCommand must be modified to call getUpdatedDocument, and to pass the document through to saveFile and save-AndPrompt. These changes are simple; and, rather than using space here we leave you to figure them out. If you want to see the changes, they're in the 5.3 folder of the sources that go with this book.

The DocumentWriter you've created follows the structure we suggested earlier, with a top-level method that writes out the top-level node (write). This calls down to writePage to write out the child page nodes. To do this, the XmlWriter has to be stored as state on the DocumentWriter, as the self.writer instance variable. Because you only have one root node, the structure is simple. You could avoid having to store state by refactoring to use an inner function.

Was this article helpful?

0 0

Post a comment